admin管理员组

文章数量:1425946

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.

本文标签: woocommerce offtopicSelect all products that have a custom field 39isnew39 set to 39Yes39