簡體   English   中英

顯示 WooCommerce 產品循環中特定類別的產品屬性值

[英]Display product attributes values for specific categories in WooCommerce product loops

我正在 WP + WooCommerce 中建立一個商店。 我有不同類型的產品類別,如光盤和包。 對於光盤產品,我有一些特定的屬性,例如 Speed、Glide、Turn 和 Fade,這些屬性沒有任何其他產品類別。 我只想在產品圖片下的商店頁面上顯示這些產品屬性值。

我找到了一個代碼,我給自己添加了一個分隔符號“|”,但是這個分隔符號現在顯示在所有可變的產品下。

是否可以將代碼更改為變量而不是僅針對特定產品類別和子類別?

在此處輸入圖像描述

代碼:

add_action( 'woocommerce_before_shop_loop_item_title', 'display_size_attribute', 5 );

function display_size_attribute() {
    global $product;
    
    if ( $product->is_type('variable') ) {
        
        $taxonomy = 'pa_speed';
        echo '<span class="attribute-speed">' . $product->get_attribute($taxonomy) . '</span>' ;
        echo ' | ';
        $taxonomy = 'pa_Glide';
        echo '<span class="attribute-Glide">' . $product->get_attribute($taxonomy) . '</span>';
        echo ' | ';
        $taxonomy = 'pa_Turn';
        echo '<span class="attribute-Turn">' . $product->get_attribute($taxonomy) . '</span>';
        echo ' | ';
        $taxonomy = 'pa_Fade';
        echo '<span class="attribute-Fade">' . $product->get_attribute($taxonomy) . '</span>';
    }
}

僅當變量產品上存在單獨的屬性值時,才使用以下重新訪問的代碼來獲取它們:

add_action( 'woocommerce_before_shop_loop_item_title', 'display_some_attributes', 5 );
function display_some_attributes() {
    global $product;

    if ( $product->is_type('variable') ) {
        $attributes = array('speed', 'Glide', 'Turn', 'Fade'); // here you defined attribute slugs
        $output     = array(); // Initializing

        // Loop through product attributes
        foreach ( $attributes as $attribute ) {
            $taxonomy = 'pa_' . $attribute;
            $values   = $product->get_attribute($taxonomy);

            // If not empty add it to the array
            if ( ! empty($values) ) {
                $output[] = '<span class="attribute-' . $attribute . '">' . $values . '</span>';
            }
        }
        // Convert array to a separated string by pipes
        echo implode(' | ', $output);
    }
}

要僅針對特定產品類別,請在代碼中替換以下塊:

    global $product;

    if ( $product->is_type('variable') ) {

with (您將在其中定義產品類別術語)

    global $product;

    $categories = array( 'cats', dogs' ); // Here your category terms ids, slugs or names

    if ( $product->is_type('variable') && has_term( $categories, 'product_cat', $product->get_id() ) ) {

代碼進入活動子主題(或活動主題)的functions.php文件。 測試和工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM