Skip to content

Instantly share code, notes, and snippets.

@ashby
Created May 1, 2014 00:43
Show Gist options
  • Select an option

  • Save ashby/11442283 to your computer and use it in GitHub Desktop.

Select an option

Save ashby/11442283 to your computer and use it in GitHub Desktop.
PHP: WP AJAX
function get_more_posts(){
$main_args = array(
'post_type' =>'post',
'post_status' => 'publish',
'posts_per_page' => $_POST['post_number'],
'paged' => $_POST['pag']
);
$main_posts = new WP_Query($main_args);
$html = '';
// the query is complete, but we didn't find anything
if( $main_posts->found_posts == 0 ){
$html .= '<div class="alert">';
$html .= 'Sorry, no more posts found.';
$html .= '</div>';
// return json
echo json_encode(array(
'html' => $html,
'have_more' => false,
'none_found' => true,
'dump' => false,
'status' => 'success',
'args' => $main_args,
));
exit;
} else {
//we found posts, now output the correct html depending on arguments
$html = '';
$post_count = 0;
while ( $main_posts->have_posts() ) {
$main_posts->the_post();
html .= '';
}
}
$have_more = true;
if( $main_posts->max_num_pages == $_POST['pag'] || $_POST['post_number'] == '-1' ){
$have_more = false;
}
$found = $main_posts->found_posts;
// return json
echo json_encode(array(
'html' => $html,
'have_more' => $have_more,
'found' => $found,
'none_found' => false,
'dump' => $main_posts->request,
'status' => 'success'
));
exit;
}
add_action('wp_ajax_get_more_posts', 'get_more_posts');
add_action('wp_ajax_nopriv_get_more_posts', 'get_more_posts');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment