Search code examples
attributeswoocommerceproductshortcode

Woocommerce add attribute info to product shortcode


I want to add a product's size attribute to the product information shown by the Woocommerce [product] shortcode.

Is there a way to do this? I don't think it is a standard parameter to the shortcode so am assuming the code will need amending?


Solution

  • You could either unregister and re-register your own version of the shortcode OR the [product] shortcode displays content via

    <?php wc_get_template_part( 'content', 'product' ); ?>
    

    Therefore you can customize the the content-product.php template in your own theme via template overrides or via hooks/filters. (The content-product.php template is mostly just a few action hooks so it looks a little sparse if you aren't familiar with hooks.)

    I would probably go the hooks route. Assuming your attribute is called "pa_size" (WooCommerce always prefaces the attribute with "pa_" so it know that the taxonomy is a "product attribute") I would add the following to my theme's functions.php

    function kia_add_size_attr(){
        global $product;
    
        $attribute_name = "pa_size";
    
        $results = wc_get_product_terms( $product->id, $attribute_name, array('fields' => 'names') );
    
        if ( $results ) {
            echo '<label>' . wc_attribute_label($attribute_name) . ': </label>' . implode( ', ', $results );
        }
    
    }
    add_action('woocommerce_after_shop_loop_item_title', 'kia_add_size_attr' );
    

    Do keep in mind that this will add the attribute to every "loop" product with a size attribute. If you only want to apply it to the shortcode, then you probably need to write your own shortcode.