2

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]

1 Answer 1

2

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"]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.