php - 从 WooCommerce 中的相关产品中排除产品类别

标签 php wordpress woocommerce custom-taxonomy taxonomy-terms

我试图从 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_inWP_Query 中用作 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',
        )
    )
);

它应该可以工作。

关于php - 从 WooCommerce 中的相关产品中排除产品类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55168292/

相关文章:

PHP lastInsertId() - 返回前一条记录编号

php - 如何将在php中创建的变量传递给mysql数据库?

wordpress - 为什么 Wordpress 默认不允许 svg 图像文件?

java - 服务器为 Java 中的 POST 请求返回 400 错误代码

plugins - WooCommerce 复合产品尝试在变体上设置 SKU 出现 "Variation SKU must be unique."错误

php - WooCommerce 中的动态同步自定义结帐选择字段

PHP:日期格式转换字符串 2010-09-02T09:46:48.78 到 dd/mm/yyyy

php - Paypal 购物车商品总金额与订单金额不符

sql - 将内容从遗留博客平台迁移到 wordpress

wordpress - 更改 Woocommerce 电子邮件模板文本