Execute add_filter inside add_action or is it possible to combine them?

451 Views Asked by At

I need to add a script to the footer if a product is added to the cart. When a product is added, it goes to the checkout page. So here on the checkout page, I need to insert the script. (Only once, when added. It will not show up after reloading the page.)

add_action( 'wp_footer', 'clearlocal' );
function clearlocal(){
  add_filter( 'woocommerce_add_cart_item_data', 'wdm_empty_cart', 10,  3);
  function wdm_empty_cart( $cart_item_data, $product_id, $variation_id ) {
     global $woocommerce;
     //Check if product ID is in a certain category
     if( has_term( 'packages', 'product_cat', $product_id ) ){
         ?><script type="text/javascript"> localStorage.clear();
         </script><?php
     }
     //Do nothing with the data and return
     return $cart_item_data;
  }
}

If a product is added from the category called packages, then I need to add the script. But I need it only when added, not always as soon as the product is in the cart.

If my goal is to show a message. Then it works just as I need.

  add_filter( 'woocommerce_add_cart_item_data', 'wdm_empty_cart', 10,  3);
  function wdm_empty_cart( $cart_item_data, $product_id, $variation_id ) {
    global $woocommerce;
    //Check if product ID is in a certain category
    if( has_term( 'packages', 'product_cat', $product_id ) ){
        wc_add_notice('Some texts','success');
    }
    //Do nothing with the data and return
    return $cart_item_data;
  }

I think the problem is add_filter is not working with add_action. I also tried this but did not work.

add_filter( 'woocommerce_add_cart_item_data', 'wdm_empty_cart', 10,  3);
function wdm_empty_cart( $cart_item_data, $product_id, $variation_id ) {
 global $woocommerce;
 //Check if product ID is in a certain category
 if( has_term( 'packages', 'product_cat', $product_id ) ){
     add_action( 'wp_footer', 'clearlocal' );
     function clearlocal(){
     ?><script type="text/javascript"> localStorage.clear();
     </script><?php
 }
 }
 //Do nothing with the data and return
 return $cart_item_data;
}
1

There are 1 best solutions below

5
On

Use wc_enqueue_js

add_filter( 'woocommerce_add_cart_item_data', 'he_check_empty_cart', 10,  3);
function he_check_empty_cart( $cart_item_data, $product_id, $variation_id ) {
    //Check if product ID is in a certain category.
    if( has_term( 'packages', 'product_cat', $product_id ) ){
        wc_enqueue_js(' localStorage.clear();' );
        }
    }
    //Do nothing with the data and return.
    return $cart_item_data;
}