Redirecting Paginated Pages in WordPress

It is typical to have one or more custom query loops on a static Page like the site’s homepage.

Let’s say in one of these you want to show the latest 5 posts without pagination.

You’d set posts_per_page to 5 and no_found_rows to true.

no_found_rows reduces the query load by telling WordPress to skip the calculation of how many rows of results are possible for your query so that it can properly set pagination. Remember to add it as a query argument anytime you have a query where pagination is not needed.

In Bricks:

You might be surprised to find that if you now visit yoursite.com/page/2, another set of 5 previous/older posts will show up!

(In our dev site, we were testing this on an inner Page)

You may take two approaches now, should you choose to – because this is a problem only if a visitor manually goes to such paginated URLs.

Either force the posts on paginated pages like /page/2, /page/3 to be the same as what’s on the homepage (this applies to WordPress queries on any static Page, homepage is taken as an example for convenience)

OR

redirect such paginated pages to the homepage.

Forcing the first set of posts

add_action( 'pre_get_posts', function ( $query ) {
    if ( is_front_page() && isset( $query->query_vars[ 'no_found_rows' ] ) && $query->query_vars[ 'no_found_rows' ] ) {
        // Force 'paged' parameter to be 1, ignoring the actual page requested.
        $query->set( 'paged', 1 );
    }
} );

Redirecting to the homepage

add_action( 'template_redirect', function () {
    if ( is_front_page() && is_paged() ) {
        wp_safe_redirect( home_url() );
        exit;
    }
} );

Reference

https://mikeyarce.com/2019/12/performant-wordpress-queries/

Instant access to 390+ Bricks code tutorials with BricksLabs Pro

Leave the first comment