Skip to content
Advertisement

WooCommerce product additional information shortcode

I am new to WooCommerce and am looking for a solution to display Product attributes on a post page. I’ve made research and some test but nothing seems to work.

Ideally, I would like to use a shortcode taking the Product ID and displaying all his product attributes on my post page. something like [product_page id="99" display_only_attributes ]

Advertisement

Answer

Here is the way to get the product attributes in a custom shortcode where you will define the product ID in as a shortcode argument id.

The function code:

if ( ! function_exists( 'display_product_additional_information' ) ) {

    function display_product_additional_information($atts) {

        // Shortcode attribute (or argument)
        $atts = shortcode_atts( array(
            'id'    => ''
        ), $atts, 'product_additional_information' );

        // 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']);
        }
        // If not we exit
        else {
            return;
        }

        ob_start(); // Start buffering

        do_action( 'woocommerce_product_additional_information', $product );

        return ob_get_clean(); // Return the buffered outpout
    }

    add_shortcode('product_additional_information', 'display_product_additional_information');

}

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

SHORTCODE USAGE (Updated)

  1. with a defined product id:

    [product_additional_information id='37']
    

    Or in php:

    echo do_shortcode("[product_additional_information id='37']");
    
  2. In an existing product page (when “additional information” product tab is removed for example):

    [product_additional_information]
    

    Or in php:

    echo do_shortcode("[product_additional_information]");
    

You will get something like this:

enter image description here

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement