Woocommerce挂钩函数的第二个参数返回NULL而不是Object

Woocommerce挂钩函数的第二个参数返回NULL而不是Object

问题描述:

In the Woocommerce documentation, the woocommerce_get_price_html filter hook located in get_price_html() method is supposed to take a callback that accepts up to two parameters, a price and a product.

But when I try to access the product, I get a NULL instead of the WC_Product Object.

Here is my testing code:

add_filter( 'woocommerce_get_price_html', function( $price, $item ) {
    echo var_dump ($item); // NULL
    return $price;
});

Am I missing something?

在Woocommerce文档中,位于 get_price_html()中的 woocommerce_get_price_html code>过滤器钩子 code>方法应该接受最多接受两个参数 strong>,价格和产品的回调。 p>

但是当我尝试访问该产品时,我得到一个 NULL code>而不是WC_Product对象。 p>

这是 我的测试代码: p>

  add_filter('woocommerce_get_price_html',函数($ price,$ item){
 echo var_dump($ item); // NULL 
返回$ price  ; 
}); 
  code>  pre> 
 
 

我错过了什么吗? p> div>

You need to declare the 2 parameters that you are using for this hook, in your hooked function, just after the hook priority, this way:

add_filter( 'woocommerce_get_price_html', function( $price, $product ) {
    echo var_dump ($product); // The WC_Product object instance
    return $price;
}, 10, 2 );

And it's better to name your function, like:

add_filter( 'woocommerce_get_price_html', 'filter_woocommerce_get_price_html', 10, 2 ); 
function filter_woocommerce_get_price_html( $price, $product ) {
    echo var_dump ($product); // The WC_Product object instance
    return $price;
}

This time you should be able to get the variable $product object…

See documentation for add_action() and add_filter() WordPress functions.

enter image description here

There are 3 places where this filter is hooked. Three of them have two parameters.

Try this way if though

add_filter( 'woocommerce_get_price_html', 'alter_price', 10, 2 );

function alter_price( $price, $item ) {
    echo var_dump ($item); 
    return $price;
}