Skip to content

Instantly share code, notes, and snippets.

@saltnpixels
Created April 10, 2016 13:15
Show Gist options
  • Save saltnpixels/fb5c22116184514ba80b71efbd0b41de to your computer and use it in GitHub Desktop.
Save saltnpixels/fb5c22116184514ba80b71efbd0b41de to your computer and use it in GitHub Desktop.
ajax with wp_query
//put into functions
// AJAX receiver function
function get_my_ajax_stuff() {
// If there's a POST and a nonce set, verify the nonce to make sure this request is coming from the right place
if ( $_POST && isset( $_POST['nonce'] ) && wp_verify_nonce( $_POST['nonce'], 'my_nonce_action' ) ) {
// Initialize
$results = array();
// Do something here to get some data (sanitize user input as needed)
$articles = new WP_Query(array(
'post_type' => 'post',
));
// Loop through articles
if ( $articles->have_posts() ) {
while ( $articles->have_posts() ) {
$articles->the_post();
$obj = new stdClass;
$obj->ID = get_the_ID();
$obj->title = get_the_title();
$obj->image = get_the_post_thumbnail( get_the_ID(), 'full' );
$obj->permalink = get_the_permalink();
$results[] = $obj;
}
wp_reset_postdata();
// Send JSON success with data
wp_send_json_success( $results );
} else {
// Send JSON error with no data message
wp_send_json_error( 'No articles found :(' );
}
} else {
// Send JSON error with nonce failure message
wp_send_json_error( 'You do not have access to this AJAX method.' );
}
}
add_action( 'wp_ajax_my_ajax_stuff', 'get_my_ajax_stuff' );
//put into your code or theme file
<!-- Example form to get AJAX stuffs -->
<form id="my-ajax-form" action="/" method="post">
<?php wp_nonce_field('my_nonce_action', 'my_nonce_id' ); ?>
<button id="get-ajax-stuff" href="#">Get AJAX Stuff</button>
</form>
<ul id="ajax-results"></ul>
<script>
jQuery(document).ready(function($) {
$('#my-ajax-form').on('submit', function(e) {
e.preventDefault();
// POST to our AJAX receiver function
$.post( '/wp-admin/admin-ajax.php', { //the file we send this to which will take our hook from functions.php
action: 'my_ajax_stuff', //used on the hook
nonce: $('#my_nonce_id').val(), //gets id from nonce we made abovea nds tores value
foo: 'bar'
}, function(response) {
console.log(response);
if ( response.success ) {
// Successful JSON response
$.each(response.data, function(index, value) {
// Append our results to our results container
$('#ajax-results').append(
$('<li>').append(
$('<a data-id="' + value.ID + '" href="' + value.permalink + '">').append(
$('<img src="' + value.image + '">'),
$('<h3>').text( value.title )
)
)
);
});
} else {
// JSON error
alert( response.data );
}
});
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment