Skip to content

Instantly share code, notes, and snippets.

@trepmal
Last active December 15, 2015 18:39
Show Gist options
  • Select an option

  • Save trepmal/5305893 to your computer and use it in GitHub Desktop.

Select an option

Save trepmal/5305893 to your computer and use it in GitHub Desktop.
WordPress priv/nopriv demo
<?php
/*
* Plugin Name: Ajax Test
* Plugin URI: trepmal.com
* Description:
* Version:
* Author: Kailey Lampert
* Author URI: kaileylampert.com
* License: GPLv2 or later
* TextDomain: some-plugin
* DomainPath:
* Network: false
*/
$Ajax_Test = new Ajax_Test();
class Ajax_Test {
function __construct() {
add_action('wp_ajax_ajax_test', array( &$this, 'ajax_test_cb') );
add_action('wp_ajax_nopriv_ajax_test', array( &$this, 'ajax_test_cb') );
add_action('wp_enqueue_scripts', array( &$this, 'load_jquery') );
add_action('admin_enqueue_scripts', array( &$this, 'load_jquery') );
add_action('wp_footer', array( &$this, 'footer_script'), 99 );
add_action('admin_footer', array( &$this, 'footer_script'), 99 );
}
function ajax_test_cb() {
die( 'hello world' );
}
function load_jquery() {
wp_enqueue_script( 'jquery' );
}
function footer_script() {
?><script>
jQuery(document).ready( function($) {
$('body').prepend( '<button id="ajax_test_btn">Test!</button>' );
var ajaxurl = '<?php echo admin_url('admin-ajax.php') ?>';
$('#ajax_test_btn').click( function() {
$.post( ajaxurl, {
action: 'ajax_test'
}, function( response ) {
$('body').prepend( '<h1>'+response+'</h1>' );
});
});
});
</script><?php
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment