Woocommerce, Get Current Product Id

Get current woocommerce product id in functions.php file

I understood the answer
in woocommerce you can't access globally product object
you have a way for handle this Issue

you should use below code in function.php

wc_get_product()->get_id();

Getting the current product ID in WooCommerce

You can get it inside Wordpress like this :

$id = $product->id;

$id = $post->id // Not working

EDIT (according to comment): Since WooCommerce 3, product properties should not be accessed directly, so $product->id will log a PHP error. Instead use $product->id().

Woocommerce, get main product id

You can get the parent id from a variation like this for example..

$main_product_id = $variation->get_parent_id();

How to get WooCommerce product object in a custom shortcode to avoid errors

To avoid this error for your custom shortcode, use the following instead:

function custom_product_description($atts){
// Extract shortcode attributes
extract( shortcode_atts( array(
'id' => get_the_ID(),
), $atts, 'product_description' ) );

global $product;

// If the product object is not defined, we get it from the product ID
if ( ! is_a($product, 'WC_Product') && get_post_type($id) === 'product' ) {
$product = wc_get_product($id);
}

if ( is_a($product, 'WC_Product') ) {
return $product->get_short_description();
}
}
add_shortcode( 'product_description', 'custom_product_description');

Code goes in functions.php file of the active child theme (or active theme). It should work now.

USAGE:

  • Without a defined id argument on single product pages: [product_description]
  • With a defined valid product ID as argument: [product_description id="37"]


Related Topics



Leave a reply



Submit