2015-04-26 30 views
1

以下代碼在我的functions.php文件中,確實會改變所有產品的重量,但我想將其隔離到特定產品。如何在過濾器'woocommerce_product_get_weight'中獲取產品ID?

add_filter('woocommerce_product_get_weight', 'rs_product_get_weight', 10, 1); 
function rs_product_get_weight($weight) { 
    $weight = 45.67; 

    return $weight; 
} 

有什麼方法可以確定我的過濾器功能中的產品ID嗎?

+0

遺憾的是沒有用那個鉤子(imo)。你想重寫插入的權重並將其保存到數據庫,或者你只需​​要在模板中顯示一個不同的值(不用觸摸數據庫)? – d79

回答

2

我不敢說,如果你看一下woocommerce get_weight功能不起作用這種方式...

public function get_weight() { 

    return apply_filters('woocommerce_product_get_weight', $this->weight ? $this->weight : ''); 
} 

也許你引用到老版本woocommerce的...

因此,舉例來說,如果你想dinamically改變購物車的商品重量,你必須掛鉤woocommerce_before_calculate_totals過濾

,並添加此功能

public function action_before_calculate(WC_Cart $cart) { 

     if (sizeof($cart->cart_contents) > 0) { 

      foreach ($cart->cart_contents as $cart_item_key => $values) { 

       $_product = $values['data']; 

       { 

       ////we set the weight 
       $values['data']->weight = our new weight; 

      } 


      } 
     } 
} 

等等...

1

這有點奇怪,但產品重量似乎來自get_weight()方法,其中有2個過濾器。您正在參考的產品ID也是woocommerce_product_weight,它確實也有產品ID。

/** 
* Returns the product's weight. 
* @todo refactor filters in this class to naming woocommerce_product_METHOD 
* @return string 
*/ 
public function get_weight() { 
    return apply_filters('woocommerce_product_weight', apply_filters('woocommerce_product_get_weight', $this->weight ? $this->weight : ''), $this); 
} 

因此,你應該能夠過濾重量:

add_filter('woocommerce_product_weight', 'rs_product_get_weight', 10, 2); 
function rs_product_get_weight($weight, $product) { 
    if($product->id == 999){ 
     $weight = 45.67; 
    } 

    return $weight; 
} 
相關問題