WP-Paginate with custom query

I’m using a custom query to retrieve only posts published in the last 30 days for a custom post type.

I have wp-paginate installed and am using it for pagination. The page itself is working fine, but wp-paginate seems to be showing enough pages for all posts, whether they were returned or not but the custom query.

Read More

For example, there are 35 published posts, but only 12 of them in the last 30 days. WP-Paginate should only display 2 pages for all 12 posts in the last 30 days, but it’s showing 4 pages, with page 3 and 4 being blank.

My code for the query is:

<?php 

$current_page = (get_query_var('paged')) ? get_query_var('paged') : 1;

function filter_where($where = '') {
    $where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
    return $where;
}

$jobPosts = null;
add_filter('posts_where', 'filter_where');
$jobPosts = new WP_Query('post_type=job_boards&paged=' . $current_page);
remove_filter('posts_where', 'filter_where');

while ($jobPosts -> have_posts()) : $jobPosts -> the_post();

    // Display stuff

endwhile; wp_reset_postdata();

if (function_exists('wp_paginate')) wp_paginate();

?>

Related posts

Leave a Reply

2 comments

  1. I seem to have solved it, though it’s way more complicated than I think it needs to be. I’m passing the number of pages and the current page to display into the wp_paginate function:

    wp_paginate(array('pages' => $num_pages, 'page' => $current_page));
    
  2. While using custom query try below

    For wp pagenavi plugin

    if (function_exists('wp_pagenavi')):
    
     wp_pagenavi( array( 'query' => $jobPosts ) );
    
    endif;
    

    For wp paginate plugin

    if (function_exists('wp_paginate')):
       wp_paginate(false,$jobPosts);
    endif;