按自定义属性对象过滤 WooCommerce 产品

Filter WooCommerce products by custom attribute object

我刚刚继承了一个 woocommerce 项目,我需要更改主页以仅显示特定品牌。他们设置了 Product-Data => Attribute => pa_brand。

如果我打印 pa_brand 数组,它会显示:

Array
(
[0] => stdClass Object
    (
        [term_id] => 1134
        [name] => Name Brand
        [slug] => name-brand
        [term_group] => 0
        [term_taxonomy_id] => 1134
        [taxonomy] => pa_brand
        [description] => 
        [parent] => 0
        [count] => 68
        [object_id] => 3385
        [filter] => raw
    )
)

我的印象是我可以使用 pa_brand 来使用其中一个键值对(最好是 slug)来过滤查询,但我不确定如何执行此操作。 None 我发现的示例有一个对象,只是字符串结果:

$args = array(
'post_type' => array('product', 'product_variation'),
'posts_per_page' => 3,
'orderby' => 'rand',
'meta_query' => array(
    array(
        'key' => 'pa_brand',
        'value' =>  array('slug' => 'brand-name'),
        'compare' => '=',
    ),
    array(
        'key' => '_stock_status',
        'value' => 'instock',
        'compare' => '='
    )
)

);

我已经尝试了很多变体,其中 none 有效。有什么建议么?

Woocommerce 属性是分类法,

假设您要创建一个品牌属性,url 结构是这样的,

yoursite.com/wp-admin/edit-tags.php?taxonomy=pa_brand&post_type=product

您看到分类名称是 pa_brand

现在,如果您在该分类法下创建像本田这样的品牌,url 就是这样,

yoursite.com/wp-admin/edit-tags.php?action=edit&taxonomy=pa_brand&tag_ID=6&post_type=product

其中本田是 pa_brand 分类法下的标签,标签 ID 为 6

现在可以在特定分类下进行 woocommerce 查询,

我们可以使用WP_query

我们可以使用这样的参数,

$args = array( 
    'post_type' => 'product', 
    'taxonomy' => 'pa_brand', // This is the taxonomy slug for brand taxonomy
    'term' => 'honda' // This is terms slug of the Honda Brand
);

如果您参考文档,上面的论点与 this

相同
$args = array(
    'post_type' => 'product',
    'tax_query' => array(
        array(
            'taxonomy' => 'pa_brand',
            'field'    => 'slug',
            'terms'    => 'honda',
        ),
    ),
);

编辑: Woocommerce 属性是分类法而不是自定义字段,

您需要使用 tax_query 而不是 meta_query,分类保存在 wp_term_taxonomywp_terms 数据库下 table,而 meta_query用于基于 Meta field/Custom 字段值的对象查询,这些字段值保存在 wp_postmeta 数据库 table、

https://codex.wordpress.org/Class_Reference/WP_Query