簡體   English   中英

從WooCommerce中的相關產品中排除產品類別

[英]Exclude a product category from Related products in WooCommerce

我想從WooCommerce的相關產品部分中排除產品類別(ID:78)。 我已經有一個自定義查詢,只顯示子類別中的相關產品。

這是我的代碼:

<?php global $post, $product;

if (empty($product) || !$product->exists()) {
    return;
}

$subcategories_array = array(0);
$all_categories = wp_get_post_terms($product->id, 'product_cat');
foreach ($all_categories as $category) {
    $children = get_term_children($category->term_id, 'product_cat');
    if (!sizeof($children)) {
    $subcategories_array[] = $category->term_id;
    }
}

if (sizeof($subcategories_array) == 1) {
    return array();
}

$args = array(
    'orderby' => 'rand',
    'posts_per_page' => 3,
    'post_type' => 'product',
    'category__not_in' => array( 78 ),
    'fields' => 'ids',
    'meta_query' => $meta_query,
    'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'field' => 'id',
            'terms' => $subcategories_array,
        )
    )
);

$wp_query = new WP_Query($args);

if ($wp_query->have_posts()):
    ?>

    <section class="related products">

    <h2><?php esc_html_e('Related products', 'woocommerce'); ?></h2>

    <?php woocommerce_product_loop_start(); ?>

    <?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?>

        <?php
        global $post, $product;

        $post_object = get_post($product->get_id());

        setup_postdata($GLOBALS['post'] = & $post_object);

        wc_get_template_part('content', 'product');
        ?>

    <?php endwhile; ?>

    <?php woocommerce_product_loop_end(); ?>

    </section>

    <?php
endif;

wp_reset_postdata();

但是,排除上述產品類別似乎並不像我預期的那樣有效。

任何幫助表示贊賞。

Woocommerce產品類別是一種自定義分類法,不能使用category__not_in作為WP_Query Wordpress category__not_in ...而是嘗試將其組合在現有的tax_query

同樣在您現有的tax_query ,對於fields參數, 您需要通過term_id替換id (默認情況下啟用,因此您可以刪除該行) ...
請參閱WP_Query Taxonomy Parameters官方文檔

請嘗試以下方法:

$args = array(
    'orderby' => 'rand',
    'posts_per_page' => 3,
    'post_type' => 'product',
    'fields' => 'ids',
    'meta_query' => $meta_query,
    'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'terms'    => $subcategories_array,
        ),
        array(
            'taxonomy' => 'product_cat',
            'terms'    => array( 78 ),
            'operator' => 'NOT IN',
        )
    )
);

它應該工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM