Skip to content

Instantly share code, notes, and snippets.

@abdallah
Created February 10, 2016 08:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abdallah/f7d3d9de386b3fba33e5 to your computer and use it in GitHub Desktop.
Save abdallah/f7d3d9de386b3fba33e5 to your computer and use it in GitHub Desktop.
WordPress ajax skeleton
<?php
/*
Plugin Name: My Plugin
Plugin URI: https://deeb.me
Description: 10 ways to peel an orange
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
function StartItUp() {
return new MyPluginClass();
}
add_action( 'init', 'StartItUp' );
class MyPluginClass {
function __construct() {
add_action( 'wp_enqueue_scripts', array( $this, 'load_scripts' ) );
add_action( 'wp_ajax_myplugin', array( $this, 'ajax_callback_myplugin_function' ) );
}
public function load_scripts() {
wp_register_script( 'myplugin',
plugins_url( 'script.js', __FILE__ ),
array( 'jquery' )
);
wp_localize_script( 'myplugin', 'params', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
) );
wp_enqueue_script( 'myplugin' );
}
function ajax_callback_myplugin_function() {
if ( check_ajax_referer( '_the_nonce', 'security' ) ) {
$somevar = $_POST['var_from_ajax_post'];
if ( $somevar === 'false' ) {
wp_send_json_success( array( 'something' => 12, 'message' => 'AOK' ) );
} else {
wp_send_json_error();
}
}
}
function add_click_link() {
$ajax_nonce = wp_create_nonce( "myplugin" );
$link = '<a href="#" class="some-link-class" id="myclicker" '
. 'data-nonce="' . $ajax_nonce . '" data-somevar="' . $varX . '">Link</a>';
return $link;
}
}
jQuery(document).ready(function ($) {
$('#myclicker').on('click', function (e) {
e.preventDefault();
var data = {
action: 'myplugin',
security: $(this).data('nonce'),
var_from_ajax_post: $(this).data('somevar'),
};
$.post(params.ajaxurl, data, function (response) {
$('#myclicker')
.data('somevar', response.data.something)
.text(response.data.message);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment