Display specific product attributes under product title in Woocommerce archive pages

≯℡__Kan透↙ 提交于 2021-02-18 18:18:48

问题


In woocommerce, I would like to show some product attributes on shop page under the product titles. This product attributes are "year", "model" and "oil".

This is what I have for now:

add_action('woocommerce_shop_loop_item_title', 'wh_insertAfterShopProductTitle', 15);

function wh_insertAfterShopProductTitle()
{
    global $product;

    $abv = $product->get_attribute('pa_year');
    if (empty($abv))
        return;
    echo __($abv, 'woocommerce');
}

Any help is appreciated.


回答1:


To display "year", "model" and "oil" product attributes under the product titles in Woocommerce archive pages as shop, use the following:

add_action('woocommerce_shop_loop_item_title', 'display_attributes_after_product_loop_title', 15);
function display_attributes_after_product_loop_title(){
    global $product;

    $output = array(); // Initializing

    // The year
    if( $year = $product->get_attribute('pa_year') ){
        // Save the value in the array
        $output[] = $year; 
    }

    // The model
    if( $model = $product->get_attribute('pa_model') ){
        // Save the value in the array
        $output[] = $model;
    }

    // The type of oil
    if( $oil = $product->get_attribute('pa_oil') ){
        // Save the value in the array
        $output[] = $oil;
    }

    // Output
    if( sizeof($output) > 0 ){
        // Display product attributes coma separated values (you can change the separator by something else below).
        echo implode( ', ', $output);
    }
}

Code goes in function.php file of your active child theme (active theme). Tested and works.



来源:https://stackoverflow.com/questions/53160122/display-specific-product-attributes-under-product-title-in-woocommerce-archive-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!