beans_loop_query_args filter


Hello all, I'm just trying to force the 'posts_per_page' argument of WP_Query to 3 and this only works for the first page (let's say I have 6 posts, the first page shows 3 posts, but when I click on "next", it shows a page with "Page not found".

Here is the code snippet in archive.php:

add_filter( 'beans_loop_query_args', function() {
    return array(
        'posts_per_page' => 3,
    );
});

If I set this in WP's settings->reading->Blog pages show at most it works fine.

Thanks for any help with this!


Odd, this only happens when I'm logged in as admin... Any idea?


Hey Marc,

Using beans_loop_query_args creates a new query so it should be used for custom loops and not to modify the main query. If it is what you need in your case, you will have to get and set the paged in the query as such:

add_filter( 'beans_loop_query_args', 'example_loop_query_args' );

function example_loop_query_args() {

 return array(
   'posts_per_page' => 3,
    'paged' => get_query_var( 'paged' ),
  );

}

If you are modifying the main query though, you should be using the pre_get_post which will keep its original query and is better performance wise. Here is an example:

add_action( 'pre_get_posts', 'example_query' );

function example_query( $query ) {

 // Modify the main query on the front end only.
 if ( $query->is_main_query() && ! is_admin() ) {
    $query->set( 'posts_per_page', 3 );
 }
}

Take a look at this article for more info about the pre_get_posts action.

Happy coding,

PS: I wrote the examples above to work with PHP 5.2 since Beans still supports it but feel free to turn it into anonymous functions for you project.


Excellent, exactly what I needed!

Thank you!

Write a reply

Login or register to write a reply, it's free!