Reputation: 85
I have a function in which i am trying to get the product short description of the current product using the product id but i keep getting Uncaught Error: Call to a member function get_short_description() on bool in
I have the following shortcode function where I am trying to get the product short description of the current WooCommerce product using the product id:
function custom_product_description( $atts ) {
global $product;
// Shortcode attribute (or argument)
$atts = shortcode_atts( array(
'id' => ''
), $atts, 'custom_product_description' );
// If the "id" argument is not defined, we try to get the post Id
if ( ! ( ! empty($atts['id']) && $atts['id'] > 0 ) ) {
$atts['id'] = get_the_id();
}
// We check that the "id" argument is a product id
if ( get_post_type($atts['id']) === 'product' ) {
$product = wc_get_product($atts['id']);
}
$product_short_description = $product->get_short_description();
return $product_short_description;
}
but I keep getting the following error:
Uncaught Error: Call to a member function get_short_description() on bool in …
Any help is appreciated.
Upvotes: 2
Views: 1758
Reputation: 253868
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:
id
argument on single product pages: [product_description]
[product_description id="37"]
Upvotes: 4