如何在WooCommerce搜索中添加产品类别参数?

时间:2016-08-09 19:49:04

标签: php sql wordpress woocommerce

我已就这方面的某些方向搜索了很多东西。我不确定我的标题是否使用了适当的用语(我相信这是我找不到解决方案的原因),所以我会陈述我的问题,也许有人可以更好地看到我和# 39; m寻找:)

我有一个WooCommerce 类别' cat-x'

当我使用WooCommerce搜索' cat-x,'一些产品有' cat-x'在他们的描述中出现,但我想包括来自' cat-x'的所有项目。在结果中。我想我想说的是:我想在搜索查询中包含类别名称。

任何帮助将不胜感激。 谢谢:)

基于这篇文章:(http://jamescollings.co.uk/blog/extending-woocommerce-search-query-include-custom-fields/), 以下是我尝试过的一些代码,但在查询后实际上没有提供任何结果:

<?php
/**
 * Add sku, author, publisher and format to product search
 */

// hook into wp pre_get_posts
add_action('pre_get_posts', 'mc_woo_search_pre_get_posts');

/**
 * Add custom join and where statements to product search query
 * @param  mixed $q query object
 * @return void
 */
function mc_woo_search_pre_get_posts($q){

    if ( is_search() ) {
        add_filter( 'posts_join', 'mc_search_post_join' );
        add_filter( 'posts_where', 'mc_search_post_excerpt' );
    }
}

/**
 * Add Custom Join Code for wp_mostmeta table
 * @param  string $join
 * @return string
 */
function mc_search_post_join($join = ''){

    global $wp_the_query;

    // escape if not woocommerce searcg query
    if ( empty( $wp_the_query->query_vars['wc_query'] ) || empty( $wp_the_query->query_vars['s'] ) )
            return $join;

    $join .= "INNER JOIN wp_postmeta AS mcmt1 ON (wp_posts.ID = mcmt1.post_id)";
    return $join;
}

/**
 * Add custom where statement to product search query
 * @param  string $where
 * @return string
 */
function mc_search_post_excerpt($where = ''){

    global $wp_the_query;

    // escape if not woocommerce search query
    if ( empty( $wp_the_query->query_vars['wc_query'] ) || empty( $wp_the_query->query_vars['s'] ) )
            return $where;

    $where = preg_replace("/post_title LIKE ('%[^%]+%')/", "post_title LIKE $1)
                OR  (mcmt1.meta_key = 'product_cat' AND CAST(mcmt1.meta_value AS CHAR) LIKE $1)
                OR  (mcmt1.meta_key = '_format' AND CAST(mcmt1.meta_value AS CHAR) LIKE $1 ", $where);

    return $where;
}
?>

0 个答案:

没有答案