skip to Main Content

I’m using the following snippet to limit the number of products in search results on my website from 10 to only 8.

However, I noticed that it’s also limiting the number of products shown via WP Admin Dashboard > Products > All Products to 8 if you use the filter. When you use the filter, it also only shows 8 products even if the filter has more than 8 products.

Is there a way to use this snippet only in search results in the front end and not in the WP Admin area?

function myprefix_search_posts_per_page($query) {
    if ( $query->is_search ) {
        $query->set( 'posts_per_page', '8' );
    }
    return $query;
}
add_filter( 'pre_get_posts','myprefix_search_posts_per_page', 20 );

2

Answers


  1. You can use woocommerce_product_query to change posts_per_page. check the below code.

    add_action( 'woocommerce_product_query', 'myprefix_search_posts_per_page', 999 );
    function myprefix_search_posts_per_page( $query ) {
    
        if( is_admin() )
            return;
    
        if ( $query->is_search() ) {
            $query->set( 'posts_per_page', '8' );
        }
    
    }
    
    Login or Signup to reply.
  2. Your function is correct. You will just need to add the is_admin() control to make sure the query is executed only in the frontend.

    Also you should add the is_main_query() control to make sure it is the main query.

    Finally, the posts_per_page parameter is an integer and not a string.

    // change the number of search results per page
    add_filter( 'pre_get_posts', 'myprefix_search_posts_per_page', 20, 1 );
    function myprefix_search_posts_per_page( $query ) {
       // only in the frontend
       if ( ! is_admin() && $query->is_main_query() ) {
          if ( $query->is_search() ) {
             $query->set( 'posts_per_page', 8 );
          }
       }
    }
    

    The code has been tested and works. Add it in your active theme’s functions.php.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search