【问题标题】:Limit search results to WooCommerce Products only in frontend仅在前端将搜索结果限制为 WooCommerce 产品
【发布时间】:2020-12-11 20:25:47
【问题描述】:

背景:

我想将搜索结果限制为仅显示 WooCommerce 产品。下面的代码正是我想要的。

//Only show products in the front-end search results
function lw_search_filter_pages($query) {
    if ($query->is_search) {
        $query->set('post_type', 'product');
        $query->set( 'wc_query', 'product_query' );
    }
    return $query;
}
 
add_filter('pre_get_posts','lw_search_filter_pages');

问题:

通过使用上面的代码,它会影响我网站上某些插件的工作方式。例如,在 Elementor Pro 中,当我搜索 Checkout Page 时,它不会出现。相反,只有Products 出现。示例截图:

有没有办法解决这个问题?

【问题讨论】:

    标签: php wordpress search woocommerce product


    【解决方案1】:

    使用! is_admin() 会将这个过滤器限制在前端,以避免后端出现很多问题:

    // Only show products in the front-end search results
    add_filter('pre_get_posts','lw_search_filter_pages');
    function lw_search_filter_pages($query) {
        // Frontend search only
        if ( ! is_admin() && $query->is_search() ) {
            $query->set('post_type', 'product');
            $query->set( 'wc_query', 'product_query' );
        }
        return $query;
    }
    

    【讨论】:

    • 我希望能够像您那样编写 Wordpress 代码。你有什么好的课程可以推荐给我吗?谢谢。
    • 几年前我刚开始为客户学习,试图通过小事解决和理解小事……以及在 StackOverflow 上我试图回答自己、理解、分析其他人代码的真实案例问题……现在我只为 WooCommerce 编写代码。
    猜你喜欢
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    相关资源
    最近更新 更多