wp-ap
wp-ap

Reputation: 109

How to run script only once when a product added to the cart in WooCommerce?

When a product is added to the cart, the page goes to the checkout page.

Here on the checkout page, I want to add a script to the footer only once when a product from a certain category is added. I mean when to reload the page it will not show up.

If I use wc_add_notice it shows a message once and when reloading the page it does not show up. Just like I want but add_action( 'wp_footer'); does not work.

add_filter('woocommerce_add_to_cart', 'my_woocommerce_add_to_cart', 8, 6);
function my_woocommerce_add_to_cart( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ){
 global $woocommerce;
 $clearstorage_cat = 30;
 $_categorie = get_the_terms($product_id, 'product_cat');
 if ($_categorie) {
     $in_cart = false;
     foreach ($_categorie as $_cat) {
         $_lacats = $_cat->term_id;
         if ($_lacats === $clearstorage_cat ){
             $in_cart = true;
         }

     }
 }


 if ( $in_cart ) {  
     function clearlocals(){        
     ?>
     <script type="text/javascript">localStorage.clear();</script>
     <?php 
     add_action( 'wp_footer', 'clearlocals' );
     }
 }
}

If I add a message, it works just as I want.

     if ( $in_cart ) {  
      wc_add_notice('Some texts','success');
      }
     

In this case, a message shows up on the checkout page only once when added.

I want to clear the local storage when a product is added to the cart.

Upvotes: 0

Views: 987

Answers (1)

Ash0ur
Ash0ur

Reputation: 1545

You can use the same notice concept. WooCommerce Sessions.

Set a session value in "AddToCart" action hook.

add_action('woocommerce_add_to_cart', 'my_woocommerce_add_to_cart', 8, 6);
function my_woocommerce_add_to_cart( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ){
 global $woocommerce;
 $clearstorage_cat = 30;
 $_categorie = get_the_terms($product_id, 'product_cat');
 if ($_categorie) {
     $in_cart = false;
     foreach ($_categorie as $_cat) {
         $_lacats = $_cat->term_id;
         if ($_lacats === $clearstorage_cat ){
             WC()->session->set( 'clear_locals, true );
         }
     }
 }

Then check inside the wp_footer action hook if it's the checkout page and session variable is set.

add_action( 'wp_footer', 'checkout_clear_locals_script' );
function checkout_clear_locals_script() {
    // Check if checkout page and session variable is set.
    if ( is_checkout() && ! is_null( WC()->session->get( 'clear_locals', null ) ) ) {
        // Clear the session variable and print the script in footer.
        WC()->session->set( 'clear_locals', null );
        ?>
        <script type="text/javascript">localStorage.clear();</script>
        <?php
    }
}

Upvotes: 1

Related Questions