在搜索结果中隐藏未分类类别中的产品

时间:2019-05-15 作者:netdev

我有大约20000种产品,我正在使用electro主题。它们都属于未分类类别(id:979),大多数也属于其他类别。我想从搜索结果中隐藏那些只属于未分类的。我还想在产品页面中隐藏未分类的类别。

我使用了此代码,它从商店页面隐藏了未分类的类别,但产品仍显示在搜索结果中:

function wc_hide_selected_terms( $terms, $taxonomies, $args ) {
    $new_terms = array();
    if ( in_array( \'product_cat\', $taxonomies ) && !is_admin() && is_shop() ) {
        foreach ( $terms as $key => $term ) {
              if ( ! in_array( $term->slug, array( \'uncategorized\' ) ) ) {
                $new_terms[] = $term;
              }
        }
        $terms = $new_terms;
    }
    return $terms;
}
add_filter( \'get_terms\', \'wc_hide_selected_terms\', 10, 3 );
这些都是试图在搜索结果中隐藏未分类(仅限)的产品,但运气不佳:

function my_electro_search_categories_filter_args($args) {
    $args[\'exclude\'] = \'uncategorized\';
    return $args;

}
add_filter(\'electro_search_categories_filter_args\', \'my_electro_search_categories_filter_args\');

function sp_pre_get_posts( $query ) {
    if ( !is_admin() && $query->is_main_query())  {
        $query->set( \'cat\', \'-979\' );
    }
}
add_action( \'pre_get_posts\', \'sp_pre_get_posts\' );

UPDATE

我用下面的答案修复了它,如下所示(但我不知道它在性能方面是否合适):

function custom_pre_get_posts_query( $q ) {

$tax_query = (array) $q->get( \'tax_query\' );

$tax_query[] = array(
    \'taxonomy\' => \'product_cat\',
    \'field\' => \'slug\',
    \'terms\' => array( \'axesouar-kinitis\', \'gnisia-axesouar\', \'axesouar-tablet-hy\', \'tilefonia\', \'statheri-tilefonia\', \'lipa-prionta\', \'exoplismos-service-norton\', \'antallaktika\' ),
    \'operator\' => \'IN\'
    //\'terms\' => array( \'uncategorized\' ),
    //\'operator\' => \'NOT IN\'
);


$q->set( \'tax_query\', $tax_query );

}
add_action( \'woocommerce_product_query\', \'custom_pre_get_posts_query\' ); 

1 个回复
SO网友:Nitish Paswan

尝试在主题函数的末尾添加以下代码行。php文件:

function custom_pre_get_posts_query( $q ) {

$tax_query = (array) $q->get( \'tax_query\' );

$tax_query[] = array(
    \'taxonomy\' => \'product_cat\',
    \'field\' => \'slug\',
    \'terms\' => array( \'uncategorized\' ),
    \'operator\' => \'NOT IN\'
);


$q->set( \'tax_query\', $tax_query );

}
add_action( \'woocommerce_product_query\', \'custom_pre_get_posts_query\' );

Reference Site

相关推荐

Slow Query On Search

请注意,我在wordpress搜索中有一个非常慢的查询,使用SHOW FULL PROCESSLIST; 下面是一个查询示例SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND (((wp_posts.post_title LIKE \'%Industreet%\') OR (wp_posts.post_excerpt LIKE \'%Industreet%\') OR (wp_posts.post_content LI