Skip to content

Instantly share code, notes, and snippets.

@hitautodestruct
Last active August 29, 2015 13:56
Show Gist options
  • Save hitautodestruct/8912729 to your computer and use it in GitHub Desktop.
Save hitautodestruct/8912729 to your computer and use it in GitHub Desktop.
Backend ajax functionality in wordpress
<?php
function request_post(){
$nonce = $_POST['nonce'];
// check to see if the submitted nonce matches with the
// generated nonce we created earlier
if ( ! wp_verify_nonce( $nonce, 'my-nonce' ) )
die ( 'Please dont');
// If you need to pass in extra information
$query_param = $_POST['query_param'];
// args
$args = array(
'posts_per_page' => 6,
'post_type' => 'post',
);
$the_query = new WP_Query( $args );
$return_pages = array();
foreach ( $the_query->posts as $page ) {
$id = $page->ID;
$return_pages[] = array(
'url' => get_permalink( $id ),
'title' => get_the_title( $id ),
'content' => substr( strip_tags( $page->post_content ), 0, 64 )
);
}
// Reset wordpress loop
wp_reset_query();
header( "Content-Type: application/json" );
echo json_encode( $return_pages );
exit();
}
// Defines the connection between the ajax request and the wordpress backend function
add_action("wp_ajax_request-post", "request_post");
// This is for users who are not logged in
add_action("wp_ajax_nopriv_request-post", "request_post");
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment