skip to Main Content

Based on Get product custom attributes to display them in WooCommerce product loop answer code.

I am displaying specific product attributes on the single product page with this:

add_action('woocommerce_single_product_summary', 'display_custom_attributes', 36 );
function display_custom_attributes() {
global $product;
$attributes_names = array('Brand', 'Color', 'Size');
$attributes_data  = array();
foreach ( $attributes_names as $attribute_name ) {
    if ( $value = $product->get_attribute($attribute_name) ) {
        $attributes_data[] = $attribute_name . ': ' . $value;
    }       
}
if ( ! empty($attributes_data) ) {
    echo '<h4>Details</h4><ul><li>' . implode( '</li><li>', $attributes_data ) . '</ul>';
}

Now I also need to add two custom meta fields (‘Serial_Number’ and ‘MPN’) to this list.

How can I add these?

2

Answers


  1. To add two custom meta fields:

    • Serial_Number
    • MPN

    to this list, you can use:

    function action_woocommerce_single_product_summary() {
        global $product;
        
        $attributes_names = array( 'Brand', 'Color', 'Size' );
    
        $attributes_data  = array();
        
        foreach ( $attributes_names as $attribute_name ) {
            if ( $value = $product->get_attribute($attribute_name) ) {
                $attributes_data[] = $attribute_name . ': ' . $value;
            }       
        }
        
        // NOT empty
        if ( ! empty($attributes_data) ) {
            echo '<h4>' . __( 'Details', 'woocommerce' ) . '</h4><ul><li>' . implode( '</li><li>', $attributes_data );
        }
        
        // Get meta
        $sn = $product->get_meta( 'Serial_Number' );    
        $mpn = $product->get_meta( 'MPN' );
        
        // NOT empty
        if ( ! empty ( $sn ) ) {
            echo '<li>' . __( 'My label 1: ', 'woocommerce' ) . $sn . '</li>';
        }
    
        // NOT empty
        if ( ! empty ( $mpn ) ) {
            echo '<li>' . __( 'My label 2: ', 'woocommerce' ) . $mpn . '</li>';
        }
        
        echo '</ul>';
    }
    add_action( 'woocommerce_single_product_summary', 'action_woocommerce_single_product_summary', 36, 0 );
    
    Login or Signup to reply.
  2. Add this code on the function.php theme file

    function call_product_meta_data()
    {
        global $post;
        if ($post) {
            $post_meta_value = get_post_meta($post->ID, 'post_meta_key', true);
            if ($post_meta_value != null) {
                echo  "<div class='pr-meta'><p><strong>Meta Title</strong>: $post_meta_value</p></div>";
            } else {
                echo  "<div class='pr-meta'><p><strong>Meta Title</strong>: N/A</p></div>";
            }
        }
    }
    add_action('woocommerce_single_variation', 'call_product_meta_data');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search