Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

php - Add Attributes to Short Description in WooCommerce 3.0+

I would like to insert the attributes from all products to their short description, so the client can open a quickview and check this attributes.

I already tried this answer: Display specific product attribute values on archives category pages

Also this one: Woocommerce - Display single product attribute(s) with shortcodes in Frontend

And I wasn't able to make it work. I think it should be because WooCommerce got updated to version 3.0+

Does anyone know a way to make it?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

to build off of LoicTheAztec's answer:

His code only works if you have predefined the attributes in the WP backend under Products -> Attributes. If you work with individual (custom) product attributes that you set up on the product page, wc_get_product_terms() won't return anything. You can recognize predefined attributes by the "pa_" prefix, they are stored in the "woocommerce_attribute_taxonomies" table.

In order to show these individual attributes in the same way as LoicTheAztec suggested, use this code:

add_action( 'woocommerce_shop_loop_item_title', 'custom_attributes_display', 20);
function custom_attributes_display()
{
    // Just for product category archive pages
    if(is_product_category())
    {
        global $product;

        // get all product attributes
        $attributes = $product->get_attributes();
        // the array of attributes you want to display (shown in same order)
        $show_attributes = array('My Attribute A', 'Another Attribute B');
        foreach($show_attributes as $key => $show_attribute)
        {
            foreach($attributes as $attribute)
            {
                // check if current attribute is among the ones to be shown
                if ($attribute->get_name() == $show_attribute)
                {
                    echo $attribute->get_options()[0];
                    // seperate attributes by "/"
                    if (count($show_attributes) > 1)
                        echo '/';
                    unset($show_attributes[$key]);
                    break;
                }
            }
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...