Created
April 26, 2014 18:15
-
-
Save nickpelton/11327034 to your computer and use it in GitHub Desktop.
WP: Ajax 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ = 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