1

I am attempting to create a custom coupon code in WooCommerce using PHP which essentially discounts the price of each item in the cart with the tag name 'main' to 10. It does this by counting the number of items in the cart tagged with 'main', then calculating the total price of each of these, and from this it calculates the required discount within the $discount variable. See below code:

$tag_name = 'main';
$tag_count = 0; 

foreach(WC()->cart->get_cart() as $cart_item)  {
    if( has_term( $tag_name, 'product_tag', $cart_item['product_id'])){
        $tag_count += $cart_item['quantity'];
        $price = $cart_item['data']->get_price();
        $float_value_price += floatval($price); 
    }
}

$discount = $float_value_price - (10*$tag_count);
$discount_string = number_format($discount, 2);


$coupon_code = 'testing'; // Code
$amount = $discount_string; // Amount
$discount_type = 'fixed_cart'; // Type: fixed_cart, percent, fixed_product, percent_product

$coupon = array(
'post_title' => $coupon_code,
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'shop_coupon');

$new_coupon_id = wp_insert_post( $coupon );

// Add meta
update_post_meta( $new_coupon_id, 'discount_type', $discount_type );
update_post_meta( $new_coupon_id, 'coupon_amount', $amount );
update_post_meta( $new_coupon_id, 'individual_use', 'no' );
update_post_meta( $new_coupon_id, 'product_ids', '' );
update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );
update_post_meta( $new_coupon_id, 'usage_limit', '' );
update_post_meta( $new_coupon_id, 'expiry_date', '' );
update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' );
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );



When I attempt to activate this code, I get the following error message:

The code snippet you are trying to save produced a fatal error on line 4:

Uncaught Error: Call to a member function get_cart() on null in /homepages/9/d392621230/htdocs/clickandbuilds/WOOCOMMERCEExperiment/wp-content/plugins/code-snippets/php/admin-menus/class-edit-menu.php(213) : eval()'d code:4 Stack trace: #0 /homepages/9/d392621230/htdocs/clickandbuilds/WOOCOMMERCEExperiment/wp-content/plugins/code-snippets/php/admin-menus/class-edit-menu.php(213): eval() #1 /homepages/9/d392621230/htdocs/clickandbuilds/WOOCOMMERCEExperiment/wp-content/plugins/code-snippets/php/admin-menus/class-edit-menu.php(263): Code_Snippets_Edit_Menu->test_code(Object(Code_Snippet)) #2 /homepages/9/d392621230/htdocs/clickandbuilds/WOOCOMMERCEExperiment/wp-content/plugins/code-snippets/php/admin-menus/class-edit-menu.php(122): Code_Snippets_Edit_Menu->save_posted_snippet() #3 /homepages/9/d392621230/htdocs/clickandbuilds/WOOCOMMERCEExperiment/wp-content/plugins/code-snippets/php/admin-menus/class-edit-menu.php(99): Code_Snippets_Edit_Menu->process_actions() #4 /homepages/9/d392621230/htdocs/clickandbuilds/W


I have been looking at this for a while now and cannot seem to find a solution. I would be grateful if anyone can solve this. Thanks.

BillyCon
  • 19
  • 2
  • Nobody can really solve this issue, as we should need to know where you are using this code… The conntext is missing from your question: *"The question should be updated to include desired behavior, a specific problem or error, **and the shortest code necessary to reproduce the problem".*** Depending on where you use this code, apparently the cart object is not defined `WC()->cart`… Don't forget that cart is a live object that is registered on a WC session and linked to a coockie on customer browser (client side). – LoicTheAztec Jun 06 '20 at 15:53

1 Answers1

0

You can achieve the same result with a simpler approach. You can create your coupon code in the WooCommerce dashboard setting it to fixed product discount.

Then with your code find the desired products and their ID's. Then you can pass those ID's to your previously created coupon by using set_product_ids(). Don't forget to save the new meta information by using save().

Then just apply the new coupon code to your cart.

The code would look something like this:

add_action( 'woocommerce_before_cart', 'cw_coupons_matched' );
function cw_coupons_matched() { 
    global $woocommerce;
    $coupon_code = 'your_discount_code';

    # Get product ID's
    foreach( WC()->cart->get_cart() as $cart_item ){
        var_dump($cart_item['data']->name);
        if (strpos($cart_item['data']->name, 'string_to_search') !== false) { 
            $product_ids[] = $cart_item['product_id'];
        }
    }

    # Adding product ID's to coupon
    $c = new WC_Coupon($coupon_code);
    $c->set_product_ids($product_ids);
    $c->save();

    # Adding discount coupon to cart
    if ( $woocommerce->cart->has_discount( $cw_coupon ) ) return;
    foreach ( $woocommerce->cart->cart_contents as $key => $values ) {
        if( in_array( $values['product_id'], $product_ids ) ) {
            $woocommerce->cart->add_discount( $coupon_code );
            wc_print_notices();
        }
    }

}