WooCommerce

Get Product Attributes Using Shortcode on WooCommerce Product Page

Updated at

I were looking for a shortcode to build product layout page on WooCommerce. Thankfully I came across a Stack Overflow answer right here. The GeneratePress elements function is really useful. So many things we can do to dress out our website. We can even customize custom post type layout using the block element and the dynamic content feature from GenerateBlocks. Anyway, here’s the code to show product attributes using shortcode, originally written by LoicTheAztec from Stack Overflow.

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');

}

Usages:

  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]");