Created
April 1, 2016 12:45
-
-
Save matheuscl/9349d3eab71e041d071e8747d82513d0 to your computer and use it in GitHub Desktop.
[WP] Load more posts using AJAX without plugins xD
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 | |
function wpajax_load_more_posts(){ | |
$page = sanitize_key( $_POST['page'] ); // Previously saved in JS or somewhere else | |
// Arguments | |
$args = array( | |
'category_name' => 'Portfolio', | |
'posts_per_page' => 6, | |
'paged' => $page | |
); | |
// The Query | |
$query = new WP_Query( $args ); | |
// The Loop | |
if ( $query->have_posts() ) { | |
$response = array( | |
'success' => true, | |
'message' => 'Posts recovered with success!', | |
'data' => $query->posts | |
); | |
} else { | |
$response = array( | |
'success' => false, | |
'message' => 'Empty posts!' | |
); | |
} | |
/* Restore original Post Data */ | |
wp_reset_postdata(); | |
echo json_encode( $response ); | |
die(); | |
} | |
add_action( 'wp_ajax_load_more_posts', 'wpajax_load_more_posts' ); | |
add_action( 'wp_ajax_nopriv_load_more_posts', 'wpajax_load_more_posts' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment