WooCommerce 通过属性查询获取产品

时间:2023-01-17
本文介绍了WooCommerce 通过属性查询获取产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个带有属性颜色的产品.属性值为红色、蓝色和绿色.我正在尝试创建自定义搜索,但无法通过查询提取任何产品.

I have a product with attribute colors. Attribute values are red, blue and green. I am trying to create a custom search but I can't get the query to pull any product.

$args =  array(
    'post_type'      => array('product'),
    'post_status'    => 'publish',
    'posts_per_page' => -1,
    'meta_query'     => array( 
        array(
            'key' => '_visibility',
            'value' => array('catalog', 'visible'),
            'compare' => 'IN',  
        ) 
    ),
    'tax_query'      => array( 
        array(
            'taxonomy'        => 'product',
            'field'           => 'slug',
            'terms'           =>  array('blue', 'red', 'green'),
            'operator'        => 'IN',
        ),
    )
);

$products = new WP_Query( $args );

我哪里做错了?

推荐答案

产品属性颜色的正确分类是 'pa_color',所以正确的工作查询是:

The correct taxonomy for the product attribute color is 'pa_color', so the correct working query is:

// The query
$products = new WP_Query( array(
   'post_type'      => array('product'),
   'post_status'    => 'publish',
   'posts_per_page' => -1,
   'meta_query'     => array( array(
        'key' => '_visibility',
        'value' => array('catalog', 'visible'),
        'compare' => 'IN',
    ) ),
   'tax_query'      => array( array(
        'taxonomy'        => 'pa_color',
        'field'           => 'slug',
        'terms'           =>  array('blue', 'red', 'green'),
        'operator'        => 'IN',
    ) )
) );

// The Loop
if ( $products->have_posts() ): while ( $products->have_posts() ):
    $products->the_post();
    $product_ids[] = $products->post->ID;
endwhile;
    wp_reset_postdata();
endif;

// TEST: Output the Products IDs
print_r($product_ids);

此代码已经过测试并且可以正常工作.您将获得所有具有颜色属性的产品,其值(术语)为蓝色"、红色"和绿色"……

This code is tested and works. You will get all products that have Color attribute with the values (terms) 'blue', 'red' and 'green'…

自 WooCommerce 3 起,产品可见性由自定义分类法 product_visibility 处理.您可以看到以下相关主题:

Since WooCommerce 3, product visibility is handled by custom taxonomy product_visibility. You can see the following related threads:

  • woocommerce 3 中产品的数据库更改
  • 在 Woocommerce 的 WP_query 中获取目录中可见的产品

这篇关于WooCommerce 通过属性查询获取产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:WooCommerce - 数量变化时自动更新总价 下一篇:Woocommerce 电子邮件通知中的样式订单详细信息表

相关文章

最新文章