質問

Every product in my database has an "pa_producator" attribute, and i want the following thing: When pa_producator is equal to "Bosch", apply an 10% discount on that product only, not on the whole cart. Is this possible? Until now i have only the following code:

add_action('woocommerce_before_cart_table', 'discount_producer');
function discount_producer( ) {
global $woocommerce;
$test = $woocommerce->cart->get_cart();
foreach($test as $product) {
  $test = get_the_terms( $product['product_id'], 'pa_producator');
  $producator = $test[0]->name;
}
}

How can i apply discount for those products?

役に立ちましたか?

解決

It's better to update values before any output. So it would apply to all places where Cart is used.

add_action('woocommerce_cart_loaded_from_session', 'check_cart_items', 99, 1);

Search for this action. This is called right after Cart is created. Then you can adjust price for each item in cart. Same way you already are trying.

public function check_cart_items($cart) {
    foreach ( $cart->cart_contents as $key => $product ) {
        // find attribute for current product
        // .. do stuff
        $cart->cart_contents[ $key ]['data']->price = $new_price;
        $cart->cart_contents[ $key ]['data']->regular_price = $price;
        $cart->cart_contents[ $key ]['data']->sale_price = $price;
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top