Search code examples
phpwordpresswoocommerceproductshortcode

Display Specific Product Attribute via a Shortcode in WooCommerce Product


With the following Code I get a Custom Product Attribute from WooCommerce.

Is this code compliant or could it be solved better?

Is the global inside the function used properly?

How can I extend the code so that if the product attribute mentioned is not present, a message "No Information on this Product" is displayed?

Functions.php

function single_atr() {
    global $product;
    $custom_attribute = $product->get_attribute( 'Color' );
    echo $custom_attribute;
}
add_shortcode( 'single_atr', 'short_ single_atr');

Shortcode in Elementor:

[short_ single_atr]

Solution

  • There are some mistakes in your current code.

    In the following, you can specify the desired product attribute to be displayed as an argument in the shortcode. If the attribute is not set on the product, a message will be displayed:

    function single_atr_shortcode( $atts ) {
        extract( shortcode_atts( array(
            'attribute' => '',
        ), $atts, 'single_atr' ) );
    
        global $product;
    
        if ( ! is_a($product, 'WC_Product') || ! $attribute ) {
            return;
        }
    
        if ( $custom_attribute = $product->get_attribute( $attribute ) ) {
            // Display product attribute
            return $custom_attribute;
        } else {
            // No attribute: Display a message
            return __("No Information on this Product", "woocommerce");
        }
    }
    add_shortcode( 'single_atr', 'single_atr_shortcode');
    

    Code goes in functions.php file of your child theme (or in a plugin). Tested and works.

    The shortcode (Usage):

    [single_atr attribute="Color"]