Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shortcode for product description in WooCommerce

Is there any shortcode to call the product description(text field under the title)?

For now, I'm using another custom field to do this job but it will be better if I use the WooCommerce field.

like image 413
Trooller Avatar asked Nov 13 '18 20:11

Trooller


2 Answers

You can build your own shortcode this way:

add_shortcode( 'product_description', 'display_product_description' );
function display_product_description( $atts ){
    $atts = shortcode_atts( array(
        'id' => get_the_id(),
    ), $atts, 'product_description' );

    global $product;

    if ( ! is_a( $product, 'WC_Product') )
        $product = wc_get_product($atts['id']);

    return $product->get_description();
}

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

Examples of USAGE [product_description]

1) In the current product page ph:

echo do_shortcode( "[product_description]" );

2) In any php code providing the related product ID

echo do_shortcode( "[product_description id='37']" );
like image 97
LoicTheAztec Avatar answered Oct 13 '22 01:10

LoicTheAztec


I wrote a very similar solution to @LoicTheAztec's answer above, but slightly more defensively (as his solution was breaking Elementor edits for me due to there not being a product context when it executes the shortcode on save).

It also solves your paragraph/newline issue as the content is formatted (basically replacing newlines with <p> tags) before returning.

function custom_product_description($atts){
    global $product;

    try {
        if( is_a($product, 'WC_Product') ) {
            return wc_format_content( $product->get_description("shortcode") );
        }

        return "Product description shortcode run outside of product context";
    } catch (Exception $e) {
        return "Product description shortcode encountered an exception";
    }
}
add_shortcode( 'custom_product_description', 'custom_product_description' );
like image 28
beveradb Avatar answered Oct 13 '22 00:10

beveradb