Add product to cart with hook, discount applies after refresh of page

I have this simple setup where I add a product to the cart as a gift if conditions are met like so:

add_action( 'woocommerce_before_cart', 'apply_membership_benefits' ); function apply_membership_benefits() {   global $  woocommerce;              // Get the cart subtotal in non-decimal number format   $  cart_subtotal = WC()->cart->subtotal;   $  product_id1 = 9617; // membership product       $  product_id2 = 9616; //  custom bottle product          // If cart subtotal is less than 800 remove benefits   if ($  cart_subtotal < 800) {       WC()->cart->remove_cart_item( WC()->cart->generate_cart_id( $  product_id1 ) );       WC()->cart->remove_cart_item( WC()->cart->generate_cart_id( $  product_id2 ) );   }       // If cart above 800 add membership benefits   if ($  cart_subtotal > 799 ) {            $  item_key_inc_cart = WC()->cart->add_to_cart( $  product_id1 );     WC()->cart->set_quantity( $  item_key_inc_cart,1 );            $  item_key_inc_cart = WC()->cart->add_to_cart( $  product_id2 );     WC()->cart->set_quantity( $  item_key_inc_cart,1 );          }  } 

The cart will work correctly only I also have a discount plugin that also applies a discount to this cart of 20%. The problem is the discount is applied if the user is refreshing the page so the cart content seems to be read before the woocommerce_before_cart hook.

Consequently if I remove one product from the cart adn the subtotal will be below 800 as shown in the example the gifts will be removed but the discount is still applied and needs a page refresh to be recalculated and eventually removed.

The discount plugin seems to add all the necessary data with these hooks

    // Prepare cart discounts     add_action('woocommerce_before_calculate_totals', array($  this, 'prepare_cart_discounts'), 1);      // Apply cart discounts     add_action('woocommerce_after_calculate_totals', array($  this, 'apply'));      // Remove no longer applicable cart discounts     add_action('woocommerce_before_calculate_totals', array($  this, 'remove_cart_discounts'), 2);     add_action('woocommerce_check_cart_items', array($  this, 'remove_cart_discounts'), 1);      // Invalidate no longer applicable cart discounts     add_filter('woocommerce_coupon_is_valid', array($  this, 'maybe_invalidate_cart_discount'), 10, 2);      // Register custom coupon type     add_filter('woocommerce_coupon_discount_types', array($  this, 'register_custom_coupon_type')); 

Hide ‘add to cart’ when certain value in dropdown is selected

Need help here please. I am trying to hide the ‘add to cart’ woocommerce button when a user selects a specific item in a dropdown list. I have tried multiple JQuery snippets in both functions.php and through 3rd party plugins but am still struggling to get it to work.

In Functions.php theme file

function load_scripts() { ?>     <script type="text/javascript">     $  (document).ready(function(){         $  (document.getElementsByName("select-1574795073993")).change(function(){             $  ( "select option:selected").each(function(){                 if($  (this).attr("value")=="International"){                     $  (".single_add_to_cart_button").hide();                 }             });         }).change();     });     </script> <?php } add_action('wp_enqueue_scripts', 'load_scripts'); 

Please can someone assist with simple steps to 1) provide correct code, and 2) insert in the hosted plarform.

Much appreciated!

Show/Hide specific shipping methods based on postcode and cart subtotal

I would like to show or hide specific shipping options based on postcode and cart subtotal amount. Here is my code:

add_filter( 'woocommerce_package_rates', 'unset_shipping_when_free_is_available', 10, 2 );     function unset_shipping_when_free_is_available( $  rates, $  package ) {      $  excluded_postcode = array( 1000,1030,1040,1050,1060,1070,1080,1081,1082,1083,1090,1140,1150,1160,1170,1180,1190,1200,1210 );     if(WC()->cart->get_cart_subtotal() >= '50' && !in_array(WC()->customer->get_shipping_postcode(), $  excluded_postcode )){         if ( isset( $  rates['free_shipping:4'] ) ) {             unset( $  rates['flat_rate:2'] );             unset( $  rates['flat_rate:26'] );             unset( $  rates['flat_rate:27'] );         }     }elseif(WC()->cart->get_cart_subtotal() >= '50' && in_array(WC()->customer->get_shipping_postcode(), $  excluded_postcode )){         if ( isset( $  rates['free_shipping:16'] ) ) {             unset( $  rates['flat_rate:13'] );             unset( $  rates['flat_rate:28'] );             unset( $  rates['flat_rate:29'] );         }     }     return $  rates; } 

What I want to do is when the customer’s postcode meets one of the list: array $ excluded_postcode(Brussels’s postcode), there will be 2 options: free collective shipping(free_shipping:16) (the customer need to choose a date) or flat rate based on weight, but if the cart subtotal is >=50€, then the shipping fee will be free, there will be also 2 options (both free), one is free collective shipping (need to choose a date) and the other is free shipping when the minimum amount is 50€(free_shipping:4); if the customer’s postcode is different from the array (not from Brussels), the shipping rate is based on weight, but if the subtotal amount is >=50€, then it will be free shipping. So if subtotal greater or equals 50€, only free options will be shown (if postcode=Brussels, 2 free shipping options: free_shipping:4 and free_shipping:16, if not Brussels: only free_shipping:4), if subtotal less than 50€, 2 options if Brussels: free_shipping:16 and flat rate based on weight, if not Brussels: only flat rate based on weight. (Brussels flat rates: flat_rate:2=0-2kg, flat_rate:26=2-5kg, flat_rate:27=5-10kg, No Brussels flat rates: flat_rate:13=0-2kg, flat_rate:28=2-5kg, flat_rate:29=5-10kg)

It works fine except when the subtotal is less than 50€ and from Brussels, only one free shipping option is showing: free_shipping:16, I would like to have both free options to be displayed.

This is the checkout page:

I would be greatful if you could help me with this, thank you!

Best way to code a shopping cart consisting of items with different properties

This is an interview question. Interviewer wanted a scalable solution

Goal is to find value of shopping cart. Cart could have 3 different types of items(Physical,Digital,URL).

Only Physical Items have a shipping address.

Only Digital items have a redeemable code that is used in a merchant site.

Only URL items have a URL that gives access to some online resource.

I’ve suggested having an Item class with price property which is extended by classes PhysicalItem, DigitalItem, UrlItem. Objects of these classes added to list which is iterated over to find the total order amount. Interviewer wasn’t impressed.

Is there any good design pattern/approach that is best applied here?

Trying to style Woocommerce sidebar Cart Widget

I have looked at length to find CSS that will change the background color, border radius and product info text color. I think this may not be a "mini cart". The price of the item, subtotal and View Cart / Checkout buttons follow the styling Ive done to the cart. I have successfully changed my product text color on my actual Cart page. So frustrating! Help is much appreciated.

Changing the Shopping cart Table order / VAT disappeared

I want to change the column order in the Shopping cart table. I want to exchange the Posititions of the Sum and VAT Column so that the Sum is the Last position. I guest the right php Template is the cart.php. Also the VAT name disappeared somehow in my column. I have VAT activated in all of my plugins and settings but it wont show :S I would be really thankful if the Pros out there could help me 🙂

enter image description here

    <?php /**  * Cart Page  *  * This template can be overridden by copying it to yourtheme/woocommerce/cart/cart.php.  *  * HOWEVER, on occasion WooCommerce will need to update template files and you  * (the theme developer) will need to copy the new files to your theme to  * maintain compatibility. We try to do this as little as possible, but it does  * happen. When this occurs the version of the template file will be bumped and  * the readme will list any important changes.  *  * @see  * @package WooCommerce/Templates  * @version 3.8.0  */  defined( 'ABSPATH' ) || exit;  do_action( 'woocommerce_before_cart' ); ?>  <form class="woocommerce-cart-form" action="<?php echo esc_url( wc_get_cart_url() ); ?>" method="post">     <?php do_action( 'woocommerce_before_cart_table' ); ?>      <table class="shop_table shop_table_responsive cart woocommerce-cart-form__contents" cellspacing="0">         <thead>             <tr>                 <th class="product-remove">&nbsp;</th>                 <th class="product-thumbnail">&nbsp;</th>                 <th class="product-name"><?php esc_html_e( 'Product', 'woocommerce' ); ?></th>                 <th class="product-price"><?php esc_html_e( 'Price', 'woocommerce' ); ?></th>                 <th class="product-quantity"><?php esc_html_e( 'Quantity', 'woocommerce' ); ?></th>                 <th class="product-subtotal"><?php esc_html_e( 'Subtotal', 'woocommerce' ); ?></th>             </tr>         </thead>         <tbody>             <?php do_action( 'woocommerce_before_cart_contents' ); ?>              <?php             foreach ( WC()->cart->get_cart() as $  cart_item_key => $  cart_item ) {                 $  _product   = apply_filters( 'woocommerce_cart_item_product', $  cart_item['data'], $  cart_item, $  cart_item_key );                 $  product_id = apply_filters( 'woocommerce_cart_item_product_id', $  cart_item['product_id'], $  cart_item, $  cart_item_key );                  if ( $  _product && $  _product->exists() && $  cart_item['quantity'] > 0 && apply_filters( 'woocommerce_cart_item_visible', true, $  cart_item, $  cart_item_key ) ) {                     $  product_permalink = apply_filters( 'woocommerce_cart_item_permalink', $  _product->is_visible() ? $  _product->get_permalink( $  cart_item ) : '', $  cart_item, $  cart_item_key );                     ?>                     <tr class="woocommerce-cart-form__cart-item <?php echo esc_attr( apply_filters( 'woocommerce_cart_item_class', 'cart_item', $  cart_item, $  cart_item_key ) ); ?>">                          <td class="product-remove">                             <?php                                 echo apply_filters( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped                                     'woocommerce_cart_item_remove_link',                                     sprintf(                                         '<a href="%s" class="remove" aria-label="%s" data-product_id="%s" data-product_sku="%s">&times;</a>',                                         esc_url( wc_get_cart_remove_url( $  cart_item_key ) ),                                         esc_html__( 'Remove this item', 'woocommerce' ),                                         esc_attr( $  product_id ),                                         esc_attr( $  _product->get_sku() )                                     ),                                     $  cart_item_key                                 );                             ?>                         </td>                          <td class="product-thumbnail">                         <?php                         $  thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $  _product->get_image(), $  cart_item, $  cart_item_key );                          if ( ! $  product_permalink ) {                             echo $  thumbnail; // PHPCS: XSS ok.                         } else {                             printf( '<a href="%s">%s</a>', esc_url( $  product_permalink ), $  thumbnail ); // PHPCS: XSS ok.                         }                         ?>                         </td>                          <td class="product-name" data-title="<?php esc_attr_e( 'Product', 'woocommerce' ); ?>">                         <?php                         if ( ! $  product_permalink ) {                             echo wp_kses_post( apply_filters( 'woocommerce_cart_item_name', $  _product->get_name(), $  cart_item, $  cart_item_key ) . '&nbsp;' );                         } else {                             echo wp_kses_post( apply_filters( 'woocommerce_cart_item_name', sprintf( '<a href="%s">%s</a>', esc_url( $  product_permalink ), $  _product->get_name() ), $  cart_item, $  cart_item_key ) );                         }                          do_action( 'woocommerce_after_cart_item_name', $  cart_item, $  cart_item_key );                          // Meta data.                         echo wc_get_formatted_cart_item_data( $  cart_item ); // PHPCS: XSS ok.                          // Backorder notification.                         if ( $  _product->backorders_require_notification() && $  _product->is_on_backorder( $  cart_item['quantity'] ) ) {                             echo wp_kses_post( apply_filters( 'woocommerce_cart_item_backorder_notification', '<p class="backorder_notification">' . esc_html__( 'Available on backorder', 'woocommerce' ) . '</p>', $  product_id ) );                         }                         ?>                         </td>                          <td class="product-price" data-title="<?php esc_attr_e( 'Price', 'woocommerce' ); ?>">                             <?php                                 echo apply_filters( 'woocommerce_cart_item_price', WC()->cart->get_product_price( $  _product ), $  cart_item, $  cart_item_key ); // PHPCS: XSS ok.                             ?>                         </td>                          <td class="product-quantity" data-title="<?php esc_attr_e( 'Quantity', 'woocommerce' ); ?>">                         <?php                         if ( $  _product->is_sold_individually() ) {                             $  product_quantity = sprintf( '1 <input type="hidden" name="cart[%s][qty]" value="1" />', $  cart_item_key );                         } else {                             $  product_quantity = woocommerce_quantity_input(                                 array(                                     'input_name'   => "cart[{$  cart_item_key}][qty]",                                     'input_value'  => $  cart_item['quantity'],                                     'max_value'    => $  _product->get_max_purchase_quantity(),                                     'min_value'    => '0',                                     'product_name' => $  _product->get_name(),                                 ),                                 $  _product,                                 false                             );                         }                          echo apply_filters( 'woocommerce_cart_item_quantity', $  product_quantity, $  cart_item_key, $  cart_item ); // PHPCS: XSS ok.                         ?>                         </td>                          <td class="product-subtotal" data-title="<?php esc_attr_e( 'Subtotal', 'woocommerce' ); ?>">                             <?php                                 echo apply_filters( 'woocommerce_cart_item_subtotal', WC()->cart->get_product_subtotal( $  _product, $  cart_item['quantity'] ), $  cart_item, $  cart_item_key ); // PHPCS: XSS ok.                             ?>                         </td>                     </tr>                     <?php                 }             }             ?>              <?php do_action( 'woocommerce_cart_contents' ); ?>              <tr>                 <td colspan="6" class="actions">                      <?php if ( wc_coupons_enabled() ) { ?>                         <div class="coupon">                             <label for="coupon_code"><?php esc_html_e( 'Coupon:', 'woocommerce' ); ?></label> <input type="text" name="coupon_code" class="input-text" id="coupon_code" value="" placeholder="<?php esc_attr_e( 'Coupon code', 'woocommerce' ); ?>" /> <button type="submit" class="button" name="apply_coupon" value="<?php esc_attr_e( 'Apply coupon', 'woocommerce' ); ?>"><?php esc_attr_e( 'Apply coupon', 'woocommerce' ); ?></button>                             <?php do_action( 'woocommerce_cart_coupon' ); ?>                         </div>                     <?php } ?>                      <button type="submit" class="button" name="update_cart" value="<?php esc_attr_e( 'Update cart', 'woocommerce' ); ?>"><?php esc_html_e( 'Update cart', 'woocommerce' ); ?></button>                      <?php do_action( 'woocommerce_cart_actions' ); ?>                      <?php wp_nonce_field( 'woocommerce-cart', 'woocommerce-cart-nonce' ); ?>                 </td>             </tr>              <?php do_action( 'woocommerce_after_cart_contents' ); ?>         </tbody>     </table>     <?php do_action( 'woocommerce_after_cart_table' ); ?> </form>  <?php do_action( 'woocommerce_before_cart_collaterals' ); ?>  <div class="cart-collaterals">     <?php         /**          * Cart collaterals hook.          *          * @hooked woocommerce_cross_sell_display          * @hooked woocommerce_cart_totals - 10          */         do_action( 'woocommerce_cart_collaterals' );     ?> </div>  <?php do_action( 'woocommerce_after_cart' ); ?> 

WooComemrce Show selected color beside color variation title and separate Add to cart button from quantity

I need some help doing such changes on my site. First of all, I want to show n selected color label to show beside Color title. and second of all, I want to show Add to cart in a separate row not in the same row with quantity. I am attaching a picture below for the reference. Pardon me if it is a silly question I am learning about WooCoomerce. w

Add specific products to cart when a button is pressed

Im making this website that is basically going to be just a 2 product page and a checkout, and due to its target audience, the idea is to have two images, 2 number boxes under them and just one button to add the products to the cart and then to redirect to the checkout page.

What i imagined is having a form, with a button, that would call a PHP function and would get the value from the number boxes and then programatically add the products to the cart (do i insert this function in functions.php ?). However after some reading i found that i may have to use AJAX to connect the HTML code to the PHP.

Do you have any suggestions? Is my way of thinking flawed?