1

I have run into some trouble with pagination using a custom query to display both private and published posts from a category.

Here's my custom query:

$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query_args = array( 
'post_type' => 'post', 'post_status' => array('private', 'publish'),
'cat' => '1208',
'posts_per_page' => 20, 'paged' => $paged, ); 

$the_query = new WP_Query( $query_args );

if ( $the_query->have_posts() ) :

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

endwhile; 
endif;

wp_pagenavi( array( 'query' => $the_query ) );

This code above works properly to logged in users, but i'm using this code to display private posts as "teasers" for guests and the private posts are being displayed but they are not being counted into the pagination calculations so we end up with less pages as it only counts the published posts.

Any idea how i can make wordpress take private posts as well as published posts into the pagination count for this custom query?

I'm stuck! Any ideas welcome! Thanks!

EDIT: Upon further investigation this code works properly if running as a "page" but when i run it as a "category" using template category-name.php wordpress will only count the posts that are "published" in the category and not include the private ones. I'm certain this is a core issue and i need to do something in functions.php to modify the query for this category.

1 Answer 1

0

If you're running this custom query in place of the normal main query, you should instead alter the main query before posts are fetched, via the pre_get_posts action. This would go in your theme's functions.php, or a custom plugin:

function wpd_private_posts_in_categories( $query ) {
    if ( $query->is_category() && $query->is_main_query() ) {
        $query->set( 'post_status', array('private', 'publish') );
        $query->set( 'posts_per_page', 20 );
    }
}
add_action( 'pre_get_posts', 'wpd_private_posts_in_categories' );

You can then run the normal loop in your category template and pagination will work properly, private posts will be included in the calculations.

1
  • Brilliant, exactly what i was looking for. Commented Mar 6, 2016 at 7:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.