2017-09-06 69 views
2

我正在根據他的類別工作,顯示SAME產品的默認差異值。 例如,我出售一張帶藍色選項&紅色的卡。 當用戶來自類別ONE時,我希望默認值爲藍色。 如果他來自TWO類別,則該值爲紅色。根據類別獲取活動的產品類別並更改SAME產品的默認差異值woocommerce

我找到一個帶有「woocommerce_product_default_attributes」元素的鉤子,但我不知道如何使用它。

注:看來即使你的產品有兩種類別


是woocommerce識別每個產品只有一類(編輯)

我有一個產品P
產品P分爲兩類:Cat 1 & Cat 2
此外,產品P有兩個變量:Blue & Red

當用戶來到由Cat 1,我想要的默認值是Blue。 如果他來了Cat 2,值將是Red

@LoicTheAztech(下同)作品的答案代碼,但是:

當我去Cat 1Cat 2,我可以看到,對於Woocommerce,該產品僅在Cat 1,甚至如果我們可以通過這兩個類別訪問。

所以在這之前,我需要解決woocommerce問題。

回答

1

在WooCommerce 3+過濾器鉤woocommerce_product_default_attributes位於get_variation_default_attributes()的方法已過時,所以它不是真正的權利掛鉤,實現你想要什麼。

get_variation_default_attributes()方法被替換爲get_default_attributes()

你可以實現你的條件函數在woocommerce_before_add_to_cart_form行動掛鉤,例如。

注:

  • 產品屬性分類總是「PA_」 +屬性蛞蝓
  • 您需要設置在變型產品的默認值的變化選項卡這個屬性開始設置。

代碼:

add_action('woocommerce_before_add_to_cart_form', function(){ 
    global $product; 

    // We EXIT if it's not a variable product 
    if(! $product->is_type('variable')) return; 

    ## DEFINE HERE the desired product attribute taxonomy 
    $pa_attribute = 'pa_color'; 
    $default_attribute_for_variation = $product->get_variation_default_attribute($pa_attribute); 

    // We EXIT if Product Attribute Color is not set as variation usage 
    if(empty($default_attribute_for_variation)) return; 

    // Get the array of default attributes 
    $default_attributes = $product->get_default_attributes(); 

    // For product category 'ONE => Attribute "blue" slug value 
    if(has_term('clothing', 'product_cat', $product->get_id())) 
     $default_attributes[$pa_attribute] = 'blue'; 

    // For product category 'TWO' => Attribute "blue" slug value 
    elseif(has_term('TWO', 'product_cat', $product->get_id())) 
     $default_attributes[$pa_attribute] = 'red'; 

    else return; // If no product categories match we exit 

    // If a product category match we set the default attribute 
    $product->set_default_attributes($default_attributes); 
}, 80, 0); 

代碼放在您的活動子主題(或主題)的function.php文件或也以任何插件文件。

此代碼已經過測試並可正常工作。

+0

嗨@LoicTheAztec,對於最近的答案感到抱歉,並感謝您的幫助!我看到了你的代碼,但我意識到一件事:Woocommerce不允許兩種類型的同一產品。事實上,SAME產品分爲兩類。當我嘗試你的代碼時,產品只能在一個.. – Efbi

+0

@Efbi這是正常的,因爲不可能爲同一產品設置2個不同的默認屬性值...因此,如果您的產品具有類別'ONE'和'TWO'它只適用於一個...因此,可能你必須更新你的問題,因爲它不夠明確。 – LoicTheAztec

+0

我更新了我的問題,是否更清楚? – Efbi

相關問題