php - How to get product specific meta data in WooCommerce

Solution:

There is multiple ways depending on what you want:

1). You will need to use on the WC_Product Object to get product properties:

$product_id = 37; // Defined product Id for testing

// Get the WC_Product Object from the product ID (optional)
$product = wc_get_product($product_id); // If needed

// Get product active price
$product_data = $product->get_price();

// … and so on …

2). For specific or custom product meta data, you will use using the desired meta key like:

$product_id = 37; // Defined product Id for testing

// Get the WC_Product Object from the product ID (optional)
$product = wc_get_product($product_id); // If needed

// Get custom meta data froma specific meta key
$product_data = $product->get_meta('my_meta_key');

// … and so on …

3). You can use instead the on the WC_Product object to get unprotected meta data in an array:

$product_id = 37; // Defined product Id for testing

// Get the WC_Product Object from the product ID (optional)
$product = wc_get_product($product_id); // If needed

// Get product unprotected meta data in an array
$product_data = $product->get_data();

// Output row data
echo '<pre>'. print_r( $obj, true ) . '</pre>';

You will get something like (extract):

Array
(
    [id] => 37
    [name] => Happy Ninja Dish Hip
    [slug] => happy-ninja-dish
    [date_created] => WC_DateTime Object
        (
            [utc_offset:protected] => 0
            [date] => 2015-12-26 11:53:15.000000
            [timezone_type] => 3
            [timezone] => Europe/Paris
        )

    [date_modified] => WC_DateTime Object
        (
            [utc_offset:protected] => 0
            [date] => 2020-07-09 19:25:32.000000
            [timezone_type] => 3
            [timezone] => Europe/Paris
        )

    [status] => publish
    [featured] => 
    [catalog_visibility] => visible
    [description] => Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet…

[add_to_cart id="53"]
    [short_description] => Pellentesque habitant morbi tristique senectus...
    [sku] => Gh2563
    [price] => 90.50
    [regular_price] => 100
    [sale_price] => 90.50

// … and so on …

Answer

Solution:

Here is Woocommerce Code Reference about how to get metadata from each product.

Also, this is example how to get metadata by key below:

function woo_custom_additional_information_tab_content() {

global $product;

$product_data = $product->get_meta('_specifications');

echo $product_data;

}

Answer

Solution:

There can be two ways to do this, One is to filter the metadata array manually in the foreach loop and other is to hit a custom query to wp_postmeta table for specific keys.

Source