0

I'm trying to modify the archive query of archive page with this function hooked to pre_get_posts action hook.

// Load our function when hook is set
add_action( 'pre_get_posts', 'rc_modify_query_limit_posts' );
function rc_modify_query_limit_posts( $query ) {

// Check if on frontend and main query is modified
if( ! is_admin() && $query->is_main_query() && $query->is_archive() ) {

    $query->set('posts_per_page', '9');

}

This is working perfectly, but somehow messes up my function for displaying current posts displayed"

function archive_post_count() {

    global $wp_query;
    $showing = '';

    if ( $wp_query->found_posts > 1 ) {

        $page_number = is_paged() ? $wp_query->query_vars['paged'] : 1;
        $current_max = ( get_option( 'posts_per_page' ) * ( $page_number - 1 ) ) + $wp_query->post_count;
        $current_min = $current_max - $wp_query->post_count + 1;

        $range   = ( $current_min == $current_max ) ? strval( $current_min ) : $current_min . '-' . $current_max;
        $total   = $wp_query->found_posts;

        $showing = 'Shown ' . $range . ' from ' . $total . ' posts ';

    }

    echo $showing;

}

Currently I have 11 posts and on first page everything works OK. But when I hit page 2 "Shown 11-12 from 11 posts" message is shown. Where is my mistake?

0

1 Answer 1

2

pre_get_posts does not explicitely changes the value in the db of posts_per_page, this value stays constant to the value set in the back end under the readings settings. pre_get_posts only changes this value before the SQL query is build in WP_Query right before the main query runs.

If you need to get the exact ( more specific ) amount of posts per page set for a specific page when using pre_get_posts, access the query vars which will hold the new value set by pre_get_posts. (NOTE: query_posts breaks the main query object, so if you use query_posts somewhere on the page, this will also fail as you will get an incorrect value. This is ONE BIG REASON why you should never ever use query_posts Here is an answer that explains this in detail.)

Instead of using

get_option( 'posts_per_page' );

use

$wp_query->query_vars['posts_per_page'];
2
  • Thank you, @Pieter Goosen! I've spotted this earlier after I reviewed my code again. For testing reasons, I changed the archive posts count in settings and also worked, but it impacts the whole blog. Thanks again! Commented Jul 2, 2015 at 11:28
  • @destructor glad it worked out for you. Enjoy :-) Commented Jul 2, 2015 at 11:52

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.