Php 在WooCommerce前端更改每页的搜索产品
我使用下面的代码片段将我网站上搜索结果中的产品数量从10个限制到8个 但是,我注意到,如果使用过滤器,它还将通过WP Admin Dashboard>products>All products显示的产品数量限制为8个。使用过滤器时,即使过滤器中的产品超过8种,它也只显示8种产品 是否有办法只在前端的搜索结果中使用此代码段,而不在WP管理区域中使用Php 在WooCommerce前端更改每页的搜索产品,php,wordpress,woocommerce,hook-woocommerce,Php,Wordpress,Woocommerce,Hook Woocommerce,我使用下面的代码片段将我网站上搜索结果中的产品数量从10个限制到8个 但是,我注意到,如果使用过滤器,它还将通过WP Admin Dashboard>products>All products显示的产品数量限制为8个。使用过滤器时,即使过滤器中的产品超过8种,它也只显示8种产品 是否有办法只在前端的搜索结果中使用此代码段,而不在WP管理区域中使用 function myprefix_search_posts_per_page($query) { if ( $query->is_se
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 );
您可以使用
woocommerce\u product\u query
更改每页的帖子。检查下面的代码
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' );
}
}
你的功能是正确的。您只需添加is_admin()
控件,以确保查询仅在前端执行
您还应该添加is\u main\u query()
控件,以确保它是主查询
最后,posts\u per\u page
参数是一个整数而不是字符串
// 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 );
}
}
}
该代码已经过测试,可以正常工作。将其添加到活动主题的functions.php中。谢谢您的建议,但这并没有将商店的搜索结果限制为8。我仍然看到默认的10。