Ad

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)

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad