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
Selecting a CSS Class With Xpath
PHP Sort Array by Subarray Value
How to Execute Two MySQL Queries as One in PHP/MySQL
Get First Key in a (Possibly) Associative Array
How to Make an Asynchronous Get Request in PHP
How to Replace Microsoft-Encoded Quotes in PHP
Using $_Post to Get Select Option Value from Html
How to Resolve Ambiguous Column Names When Retrieving Results
How to Write a PHP Ternary Operator
How to Have a 64-Bit Integer in PHP
Does $_Server['Http_X_Requested_With'] Exist in PHP or Not
A Numeric String as Array Key in PHP
How to Load a Controller from Another Controller in Codeigniter
Call to a Member Function Prepare() on a Non-Object PHP Help