1
votes

I want to add a discount for all products in a category. I've tried this function here:

add_filter( 'woocommerce_get_price', 'custom_price_sale', 10, 2 );
function custom_price_sale( $price, $product ) {
if ( has_term( 'promocje-i-outlet', 'product_cat' ) ) {
   $price = $price * ( 1 - 0.25 );
}
return $price;
}

When I'm using just this without the if():

$price = $price * ( 1 - 0.25 );

it works perfectly and I see the discount on the single product page, in cart widget, on cart page, on checkout page and in an order. But when I try to set the discount to a specific product in a category, the product get's added to cart with regular price and without the discount.

I've also tried to use this here:

get_the_terms( $product->ID, 'product_cat' );

Then make array of categories and use this:

if ( in_array( 'promocje-i-outlet', $kategoria ) ) {
    $price = $price * ( 1 - 0.25 );
}

But the effect is the same - dynamic pricing isn't working and I get this warning:

Warning: in_array() expects parameter 2 to be array, null given

What am I doing wrong?

1

1 Answers

1
votes

I'm not 100% sure but this can't work because this is within a function which loops over all products during the page build. The has_term function can't work here because it only works when you're on a specific single-product page.

Try this here instead:

add_filter( 'woocommerce_product_get_price', 'custom_sale_price_for_category', 10, 2 );
function custom_sale_price_for_category( $price, $product ) {

    //Get all product categories for the current product
    $terms = wp_get_post_terms( $product->get_id(), 'product_cat' );
    foreach ( $terms as $term ) {
        $categories[] = $term->slug;
    }

    if ( ! empty( $categories ) && in_array( 'promocje-i-outlet', $categories, true ) ) {
        $price *= ( 1 - 0.25 );
    }

    return $price;
}

Please tell me if it works.