Hi there I am developing a theme where I have to load some posts with ajax, in my index page everything works properly, the problem is when I need to use it on custom post type, I pass the values for a jquery file using wp_localize_script, it pass the correct value when I have regular posts, but it always pass 0 when I have a custom post type. Can you help me? Many thanks.
Code to pass arguments to my jQuery script
function core_ajax_init() {
global $wp_query;
// Add code to index pages.
if( !is_admin() ) { //!is_singular()
// Enqueue jQuery Script to Process Ajax
wp_enqueue_script(
'core_custom',
get_template_directory_uri(). '/core/js/ajax-load-posts.js',
array('jquery'),
'1.0',
true
);
// What page are we on? And what is the pages limit?
$max = $wp_query->max_num_pages;
$paged = ( get_query_var('paged') > 1 ) ? get_query_var('paged') : 1;
//echo $max;
// Add some parameters for the JS.
wp_localize_script(
'core_custom',
'core',
array(
'startPage' => $paged,
'maxPages' => $max,
'nextLink' => next_posts($max, false)
)
);
}
}
add_action('template_redirect', 'core_ajax_init');
The following is a template where I call to print the button to load more posts
<?php
global $wp_query;
$found_posts = $wp_query->found_posts;
$per_page = get_option('posts_per_page');
$post_count = $found_posts - $per_page;
if($found_posts > $per_page) :
?>
<div class="row" id="load-more" data-order='999'>
<div class="col-md-12">
<div class="load-more-btn">
<a id="load-more-btn" href="#">
<span id="detail-holder">
<div id="loader" data-perpage="<?php echo $per_page; ?>"></div>
<div class="load-more-text"><?php _e('Click here to load more', CORE_THEME_NAME); ?></div>
</span>
</a>
</div>
</div> <!-- /.col-md-12 -->
</div> <!-- /.row -->
<?php endif; ?>
And here I have a snippet where I make a custom query for a specific post type
global $wp_query;
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$wp_query = new WP_Query(array( 'post_type' => 'course', 'order' => 'DESC', 'orderby' => 'date', 'paged' => $paged ));
if($wp_query->have_posts()): ?>
The problem here is it seems no matter how many pages I have wp_query var here always return 0 to my function core_ajax_init(), if I have regular posts it returns the correct number of pages but for custom post type it always returns 0. Why? Thank you for your answers.
Yuo can also do it this way, count published posts, get settings posts per page, then divide.