简体   繁体   中英

Get all WooCommerce products from a category that have specific meta data

I have a custom meta on my custom post type:

$arr = array('foo' => 'yes',
             'featured_enabled' => 123,
             'something' => 'abc',
);

update_post_meta($post_id, 'fvp_featured_meta', $arr );

My question is how can I get all products from specific category ID in woocommerce that have this meta (fvp_featured_meta)? (not all posts have this meta)

You can try to use wc_get_products() function to get products that have a specific meta data belonging to a specific product category as follows:

$category_term_slugs = array('clothing'); // <== Define your product category

// Get an array of WC_Product Objects
$products = wc_get_products( array(
    'limit'         => -1,
    'status'        => 'publish',
    'meta_key'      => 'fvp_featured_meta',
    'meta_compare'  => 'EXISTS',
    'category'      => $category_term_slugs,
) );

echo '<ul>';

// Loop Through products array
foreach( $products as $product ) {
    $product_name = $product->get_name();
    $meta_array   = $product->get_meta('fvp_featured_meta'); // Get meta data (array)
    $meta_output  = []; // Initializing

    if( ! empty( $meta_array ) ) {
        // Loop through custom field array key/value pairs
        foreach( $meta_array as $key => $value ) {
            $meta_output[] = $key . ': ' . $value;
        }
        $meta_output = ' | ' . implode(' | ', $meta_output);
    }
    
    echo '<li>' . $product_name . $meta_output . '</li>';
}

echo '</ul>';

It should works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM