最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

woocommerce offtopic - Select all products that have a custom field 'is_new' set to 'Yes'

programmeradmin1浏览0评论

How can I select all products that have a custom field 'is_new' set to 'Yes'?

This is what I tried:

$loop = new WP_Query([
    'post_type'         => 'product',
    'posts_per_page'    => -1,
    'tax_query'         => [
        'taxonomy'      => 'is_new',
        'terms'         => 'YES',
        'operator'      => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'.
    ]
]);

Unfortunately, this just gives me all products.

How can I select all products that have a custom field 'is_new' set to 'Yes'?

This is what I tried:

$loop = new WP_Query([
    'post_type'         => 'product',
    'posts_per_page'    => -1,
    'tax_query'         => [
        'taxonomy'      => 'is_new',
        'terms'         => 'YES',
        'operator'      => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'.
    ]
]);

Unfortunately, this just gives me all products.

Share Improve this question edited May 30, 2019 at 21:08 butlerblog 5,1313 gold badges28 silver badges44 bronze badges asked May 30, 2019 at 20:12 AndrewAndrew 1
Add a comment  | 

1 Answer 1

Reset to default 0

You're attempting to do a "taxonomy query". This is for things like tags and categories. Custom fields are stored as meta, so you need to do a meta query.

$loop = new WP_Query( [
    'post_type'      => 'product',
    'posts_per_page' => -1,
    'meta_query'     => [
        [
            'key'   => 'is_new',
            'value' => 'Yes',
        ],
    ],
] );

There's a few other differences to take note of:

  • From your screenshot, the value for yes is Yes, not YES.
  • Taxonomy and meta queries need to be an array of arrays. See how my meta query is an array inside another array.
  • Since it's not a taxonomy query, we use compare instead of operator, but the default value for that is =, which we want, so we can omit it.
发布评论

评论列表(0)

  1. 暂无评论