首页 文章

WordPress默认搜索和Woocommerce产品搜索

提问于
浏览
0

我试图让搜索工作默认的WordPress博客搜索和WooCommerce产品搜索时遇到问题,我似乎无法在任何地方找到解决方案 . 我现在在functions.php中有的是:

function wp_search_filter($query) {
    if ( $query->is_search ) {
        $query->set( 'post_type', 'post' );
    }
    if ( function_exists( 'is_woocommerce' ) ) : 
        if ( $query->is_search && is_woocommerce() ) {
            $query->set( 'post_type', 'product' );
        }
    endif;
    return $query;
 }
add_filter('pre_get_posts','wp_search_filter');

但我的产品搜索不起作用 . 有任何想法吗?

1 回答

  • 0

    要回答我自己的问题,如果有人需要解决方案,我只想出一些有效的方法 . 这里的问题是is_woocommerce()条件没有在搜索结果模板上触发 . 为了解决这个问题,我使用了以下代码:

    function wp_search_filter($query) {
        $url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
        if ( (strpos($url,'post_type=product') !== false) && is_search() ) {
            $query->set('post_type', 'product');
        }
        return $query;
    }
    
    add_filter('pre_get_posts','wp_search_filter');
    

相关问题