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.