【问题标题】:Exclude a product category from Related products in WooCommerce从 WooCommerce 中的相关产品中排除产品类别
【发布时间】:2019-08-05 16:31:37
【问题描述】:

我正在尝试从 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();

但是,排除上述产品类别似乎并没有像我预期的那样工作。

感谢任何帮助。

【问题讨论】:

    标签: php wordpress woocommerce custom-taxonomy taxonomy-terms


    【解决方案1】:

    Woocommerce 产品类别是一种自定义分类法,不能在 WP_Query 中使用 category__not_in 用作 Wordpress 类别……而是尝试将其组合到现有的 tax_query 中。

    同样在您现有的tax_query 上,对于fields 参数您需要将id 替换为term_id (默认启用,因此您可以删除该行)
    WP_Query Taxonomy Parameters official documentation

    尝试以下方法:

    $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',
            )
        )
    );
    

    它应该可以工作。

    【讨论】:

    • 这肯定比以前工作得更好......如果当前产品属于 id 78 的类别,是否可以修改此查询以显示随机选择的“相关产品”?跨度>
    猜你喜欢
    • 2018-11-09
    • 2013-08-11
    • 2018-05-17
    • 1970-01-01
    • 2019-07-15
    • 2019-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多