Last active
November 19, 2015 11:48
-
-
Save hitautodestruct/10018243 to your computer and use it in GitHub Desktop.
The basics of creating an internal wordpress ajax request.
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 | |
// Inside functions.php | |
function get_category_posts(){ | |
$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 ( 'Requested resource is not accessible.' ); | |
$category_id = $_REQUEST['categoryId']; | |
// args | |
$args = array( | |
'posts_per_page' => -1, | |
'post_type' => 'hozer', | |
'post_status' => 'publish', | |
'cat' => $category_id | |
); | |
$return_pages = array(); | |
$the_query = new WP_Query( $args ); | |
$posts = $the_query->posts; | |
if ( $posts ) { | |
foreach ( $posts as $page ) { | |
$id = $page->ID; | |
$return_pages[] = array( | |
'title' => get_the_title( $id ) | |
); | |
} | |
// Reset wordpress loop | |
wp_reset_query(); | |
} | |
header( "Content-Type: application/json" ); | |
echo json_encode( $return_pages ); | |
exit(); | |
} | |
add_action("wp_ajax_get-category-posts", "get_category_posts"); | |
add_action("wp_ajax_nopriv_get-category-posts", "get_category_posts"); | |
// When adding a script via wordpress add the nonce as well | |
// See https://gist.github.com/hitautodestruct/8912648#file-add-scripts-php-L31 | |
// For example of how to add nonce and js scripts | |
?> | |
<script> | |
var sendParams = { | |
action: 'get-category-posts', | |
nonce: mainScriptParams.Nonce | |
}; | |
var getPosters = function( options ) { | |
html = []; | |
$.post( '/wp-admin/admin-ajax.php', params ) | |
.done(function( data ){ | |
data.forEach(function(item) { | |
html.push( '<li>'+ item.title +'</li>' ); | |
}); | |
$('#resultWrapper').html( html.join('') ); | |
showLoading(false); | |
}) | |
.fail(function( err ){ showLoading(false); }); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment