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
You can use
woocommerce_product_query
to changeposts_per_page
. check the below code.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.The code has been tested and works. Add it in your active theme’s functions.php.