在 Woocommerce 中隐藏宏类别中的子类别产品

问题描述 投票:0回答:2

我想显示宏观类别的产品和子类别,但我不想显示子类别的产品。

这是我的问题的一个例子:http://www.idromet.it/jml/wp/categoria-prodotto/prodotti/tubi-raccordi-acciaio-al-carbonio/

“Raccordi in ghisanzati”显示了两次,因为第一个是类别(及其右侧),第二个是该子类别的产品我不想在这里显示它)。

wordpress woocommerce
2个回答
7
投票

下面的代码应粘贴到位于子主题文件夹中的functions.php文件中。

function exclude_product_cat_children($wp_query) {
if ( isset ( $wp_query->query_vars['product_cat'] ) && $wp_query->is_main_query()) {
    $wp_query->set('tax_query', array( 
                                    array (
                                        'taxonomy' => 'product_cat',
                                        'field' => 'slug',
                                        'terms' => $wp_query->query_vars['product_cat'],
                                        'include_children' => false
                                    ) 
                                 )
    );
  }
}  
add_filter('pre_get_posts', 'exclude_product_cat_children'); 

0
投票

此代码仅显示当前类别的产品。隐藏父类别和子类别。可以使用简码 [cwpai_current_category_products] 触发代码

    function cwpai_show_products_from_current_category() {
        if (!is_product_category()) return;

$current_term = get_queried_object();
$args = array(
    'post_type' => 'product',
    'posts_per_page' => -1,
    'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'field' => 'term_id',
            'terms' => $current_term->term_id,
            'include_children' => false
        )
    )
);
$products = new WP_Query($args);

if ($products->have_posts()) {
    echo '<ul class="products">';
    while ($products->have_posts()) : $products->the_post();
        wc_get_template_part('content', 'product');
    endwhile;
    echo '</ul>';
}

wp_reset_postdata(); }

add_shortcode('cwpai_current_category_products', 
'cwpai_show_products_from_current_category');

   function cwpai_hide_subcategory_icons() {
    if (is_product_category()) {
        add_filter('subcategory_archive_thumbnail', '__return_false');
    }
}

add_action('woocommerce_before_main_content', 'cwpai_hide_subcategory_icons');
© www.soinside.com 2019 - 2024. All rights reserved.