Php 如何在过滤器';woocommerce产品的重量是多少;?
下面的代码在我的functions.php文件中,确实改变了所有产品的权重,但我想将其隔离到一个特定的产品中Php 如何在过滤器';woocommerce产品的重量是多少;?,php,wordpress,woocommerce,Php,Wordpress,Woocommerce,下面的代码在我的functions.php文件中,确实改变了所有产品的权重,但我想将其隔离到一个特定的产品中 add_filter('woocommerce_product_get_weight', 'rs_product_get_weight', 10, 1); function rs_product_get_weight($weight) { $weight = 45.67; return $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吗?这有点奇怪,但产品权重似乎来自
get\u weight()
方法,该方法内部有两个筛选器。您正在引用的一个,也是woocommerce\u product\u 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;
}
我不敢说这样不行。。。 如果你看一看加权函数
public function get_weight() {
return apply_filters( 'woocommerce_product_get_weight', $this->weight ? $this->weight : '' );
}
也许你指的是旧版本的woocommerce
因此,例如,如果您想动态更改购物车产品重量,您必须在计算总计过滤器之前钩住woocommerce\u
并添加此函数
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;
}
}
}
}
等等…不幸的是,没有这个钩子(imo)。是要覆盖插入的权重并将其保存到数据库中,还是只需要在模板中显示不同的值(不接触db)?