Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am using a function to automatically apply a coupon for certain products.The coupon only applies to a single category and is for a one-time event where those customers are only presented this limited range of products.

add_action( 'woocommerce_before_cart_table', 'apply_matched_coupons' );

function apply_matched_coupons() {
    global $woocommerce;

    $coupon_code = 'ofa'; // your coupon code here

    if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

    if ( $woocommerce->cart->cart_contents_total >= 21 ) {
        $woocommerce->cart->add_discount( $coupon_code );
        $woocommerce->show_messages();
    }
}

This works fine for these special event customers. However for other regular customers they will get an error message about the coupon not applying towards the products they are purchasing. I'd like to avoid that.

So I tried wrapping the action in a condition that it only run when a particular product is in the cart, but it causes an error. Can anyone suggest what is wrong. Thanks for any help.

 foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
    $_product = $values['data'];
        if ( $_product->id == '44879' )
            add_action( 'woocommerce_before_cart_table', 'apply_matched_coupons' );
}
share|improve this question
    
Please be more specific on "it causes an error". What is the expected behaviour? What is the actual behaviour? Are you getting PHP errors or is the code simply not functioning as you expect it to? –  engelen Mar 29 at 21:09
    
Sorry the error is Fatal error: Call to a member function get_cart() on a non-object (in the 1st line) What I expect is that if the product is 44879 the action should fire, otherwise it shouldn't. I would mention the code in the first 3 lines of that condition (foreach and if clause) are from docs.woothemes.com/document/… –  jim Mar 30 at 3:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.