3

I'm customizing a Woocommerce Wordpress site.

In the Woocommerce product class (class-wc-product.php) the get_price function applies a filter as follows:

function get_price() {
    return apply_filters('woocommerce_get_price', $this->price, $this);
}

In my functions.php I want to add a filter as follows:

add_filter('woocommerce_get_price', 'custom_price');

function custom_price($price, $product) {
    ...
}

When I call this I get the following PHP warning:

Warning: Missing argument 2 for custom_price()

Why is the second argument missing? Is $this not sent to the filter call?

2
  • Maybe apply_filters('woocommerce_get_price', … ); is called somewhere else without the second argument? Did you search for such a case?
    – fuxia
    Nov 12, 2012 at 15:10
  • It's called only once as far as I can see
    – benedict_w
    Nov 12, 2012 at 15:12

2 Answers 2

14

It's missing the second argument because you didn't tell WordPress you wanted it with your add_filter call. By default, actions and filters only get one argument. Try this:

<?php
add_filter('woocommerce_get_price', 'custom_price', 10, 2);

function custom_price($price, $product) {
    ...
}
2
  • Good answer Chris, exactly why I love this site. I learn something new every day.
    – Steve
    Nov 12, 2012 at 16:10
  • For the longest time I didn't even know the value for parameter 4 dictates the number of arguments to pass in. TY
    – Antony
    Feb 21, 2018 at 22:17
1

The warning is a result of the second argument in your function custom_price(). The filter provides only one variable on the call and I can't remember if this is the product/post ID or the price. The code docs indicate that it returns a string so I'd presume it's the price.

You can hopefully find the documentation at http://wcdocs.woothemes.com/apidocs/index.html

If you need the product at this point you'll have to use:

function custom_price( $price ) {

    global $product;

}

If all else fails simply echo $price to see if you can tell if it's a product ID or a price. Then adjust your code accordingly.

2
  • Thanks for your insights @chrisguitarguy's anwser seems to have done the trick for me.
    – benedict_w
    Nov 12, 2012 at 15:52
  • Yeah, it's certainly a more elegant solution.
    – Steve
    Nov 12, 2012 at 16:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.