Skip to content

Instantly share code, notes, and snippets.

@nickpelton
Created April 26, 2014 18:15
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 nickpelton/11327034 to your computer and use it in GitHub Desktop.
Save nickpelton/11327034 to your computer and use it in GitHub Desktop.
WP: Ajax 2
<?php
/**
* Setup JSON Ajax endpoint for Javascript async access to WP data
*/
add_action('wp_ajax_load_posts', 'load_post_callback'); // Enable for logged-in users
add_action('wp_ajax_nopriv_load_posts', 'load_post_callback'); // Enable for anonymous users
function load_post_callback(){
// Get some data from WP
$args = array(
'post_type'=>'post',
'posts_per_page' => 3
);
$posts_array = get_posts($args);
// Return data as JSON string
wp_send_json($posts_array);
}
// output: http://presentation.dev/demo/wp-admin/admin-ajax.php?action=my_action_4
<?php
// enque script
wp_enqueue_script( "myScript", site_url()."/assets/s4/myscript.js", array('jquery'), '1.0',true);
// Setup our data
$myDataArray = array(
'ajax_url' => admin_url( 'admin-ajax.php' )
);
// Pass data to myscript.js on page load
wp_localize_script( "myScript", "myLocalizedData", $myDataArray );
// wp_localize_script( $handle, $objectName, $arrayOfValues );
// $handle - The enqueued script to place the data immedietly before
// $objectName - Name of the JS object that will hold the data
// $arrayOfValues - Data to pass to JS
$ = jQuery.noConflict();
jQuery(document).ready(function(){
/**
* js-load-posts
*
* Accessing JSON data using AJAX from WP to JS after page load with user action
*/
$('#btn_events').on('click','.js-ajax-get-data',function(e){
// Access WP data using $.ajax()
$.ajax({
method: "POST",
dataType: "JSON",
url: myLocalizedData.ajax_url,
data: {action:"load_posts"},
}).done(function(myAjaxData){
html = "";
$.each(myAjaxData,function(index,value){
html += "<h3>"+value.post_title+"</h3><br>";
html += "<div>"+value.post_content+"</div><br><br>";
});
$('#displayData').append(html); // Note one insert
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment