Adding several meta fields to WooCommerce single product page

Viewed 225

I am displaying a custom meta field on the single product page:

function my_custom_field() {
global $product;
$value = get_post_meta( $product->id, 'color', true );

if ( ! empty( $value ) ) {
echo $value;
}

add_action('woocommerce_single_product_summary', 'my_custom_field', 30 );

Now I have several more custom fields that need to be displayed (just the values, not the labels).

How can I add these onto the code?

1 Answers

This will display several meta fields on the WooCommerce single product page.

Explanation via comment tags added to my answer:

function action_woocommerce_single_product_summary() {
    // Add meta keys, multiple can be added separated by a comma
    $meta_keys = array( 'color', 'lot_number', '_missing_stock', '_rating' );

    // Get the global product object
    global $product;
    
    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        foreach ( $meta_keys as $meta_key ) {
            // Get meta value
            $value = $product->get_meta( $meta_key );

            // NOT empty
            if ( ! empty ( $value ) ) {
                echo '<p>' . $value . '</p>';
            }
        }
    }
}
add_action( 'woocommerce_single_product_summary', 'action_woocommerce_single_product_summary', 10, 0 );

Note: Since WooCommerce 3 (2017) $product->id needs to be $product->get_id() in your code. However, it is also possible without using it, as you can see in my answer

Related