1
votes

Is there a way to display the current product SKU and GTIN in a variable product page? Right now I'm using the following code, but it only works for simple products without variations:

add_action('woocommerce_single_product_summary', 'show_sku_and_gtin');
function show_sku_and_gtin() {
  global $product, $post; 
  echo '<p>SKU: '.$product->sku.'</p>';
  // In my case, GTIN is a custom field called "barcode"
  echo '<p>GTIN: '.get_post_meta($post->ID, 'barcode', 1).'</p>';                    
}

I'd like it to update the SKU and GTIN dynamically whenever I choose a different product variation in the product page.

1

1 Answers

2
votes

Update (for your existing code at the end)

To make that possible for variation products, we will use the dynamic variation description to insert the SKU and the GTIN and display them dynamically:

// Display product variations SKU and GTIN info
add_filter( 'woocommerce_available_variation', 'display_variation_sku_and_gtin', 20, 3 );
function display_variation_sku_and_gtin( $variation_data, $product, $variation ) {
    $html = ''; // Initializing

    // Inserting SKU
    if( ! empty( $variation_data['sku'] ) ){
        $html .= '</div><div class="woocommerce-variation-sku">' . __('SKU:') . ' ' . $variation_data['sku'];
    }

    // Inserting GTIN
    if( get_post_meta( $variation->get_id(), 'barcode', true ) ){
        $gtin = get_post_meta( $variation->get_id(), 'barcode', true );
        $html .= '</div><div class="woocommerce-variation-gtin">' . __('GTIN:') . ' ' . $gtin;
    }

    // Using the variation description to add dynamically the SKU and the GTIN
    $variation_data['variation_description'] .= $html;

    return $variation_data;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.


Now your answer code is a bit outdated since Woocommerce 3 and with some errors.

Also you should exclude varible products from it as with my answer code, you get now the SKU and GTIN for product variations of the variable products.

Here is the revisited code:

add_action('woocommerce_single_product_summary', 'display_product_sku_and_gtin', );
function display_product_sku_and_gtin() {
    global $product; 

    echo '<p>' . __("SKU:") . ' ' . $product->get_sku() . '</p>';

    if( get_post_meta( $product->get_id(), 'barcode', true) )
        echo '<p>' . __("GTIN:") . ' ' . get_post_meta( $product->get_id(), 'barcode', true) . '</p>';                  
}

Code goes in function.php file of your active child theme (or active theme).