questions

How to get product data in header.php file wordpress woocommerce

Rate this post

I want to show something of product like: name, price, sku in the header.php file. Below is my code to get product in header.php

global $product;
var_dump($product);

But var_dump just show me the product name like string(6) "hoodie", not array of product.

So, how can I get the product data in header.php file.

Thank you.

 

✔️Solution:

Use the WordPress get_the_ID() function.

Obviously this will only work if you are on the product page, so you can add an extra control with WooCommerce’s is_product() function.

Finally, to add custom code in the header you can use the wp_head hook.

So the function will look like:

// gets the product data in the header
add_action( 'wp_head', 'get_product_data' );
function get_product_data() {
    // only on the product page
    if ( ! is_product() ) {
        return;
    }
    // gets the product object
    $product = wc_get_product( get_the_ID() );
    ?>
    HTML CODE HERE
    <?php
}

Tested and it works. The code goes into your active theme’s functions.php file.

Leave a Reply

Your email address will not be published.

Back to top button