在 WooCommerce 前端更改每页的搜索产品

Alter Search Products per Page in WooCommerce Front End

我正在使用以下代码段将我网站上搜索结果中的产品数量从 10 个限制为仅 8 个。

但是,我注意到如果您使用过滤器,它还会将通过 WP 管理仪表板 > 产品 > 所有产品显示的产品数量限制为 8 个。当您使用过滤器时,它也只显示 8 个产品,即使过滤器有 8 个以上的产品。

有没有办法只在前端的搜索结果中而不是在 WP 管理区域中使用此代码段?

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_product_query更改posts_per_page。检查下面的代码。

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_main_query() 控件以确保它是主查询。

最后,posts_per_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.