Home > other >  "Update Cart" not triggering my woocommerce_after_cart_totals action hook
"Update Cart" not triggering my woocommerce_after_cart_totals action hook

Time:02-08

I have a woocommerce_after_cart_totals hook action being done to output a specific JSON object to the cart page. It works as expected on page load, however when someone changes qty and hits Update Cart button, the JSON variable disappears and a new one is not recreated.

add_action('woocommerce_after_cart_totals','custom_json_var_output',10,2);
function custom_json_var_output(){
    //build the variable to $output
    //............
    echo "<script>jsonCartData=".json_encode($output).";</script>";
}

So on cart page load i see jsonCartData=*********** script tag below cart_totals div, but when Update Cart is clicked, my tag disappears entirely.

I need to know why this is the case, and what additional action I need to trigger to get the new output after the cart_totals div when Update Cart is done. Why would an update cart action not include retriggering the woocommerce_after_cart_totals hook?

CodePudding user response:

This is because each time something changes, an Ajax request is made and the corresponding sections on the page are updated.

If you want to hook into the Ajax calls, you should use the woocommerce_add_to_cart_fragments filter.

function filter_woocommerce_add_to_cart_fragments(array $array): array
{
    // Your logic …

    $array['#my-script-css-selector'] = <<<HTML
    <script id=my-script-css-selector>
        console.log('hello')
    </script>
    HTML;
    return $array;
};

add_filter('woocommerce_add_to_cart_fragments', 'filter_woocommerce_add_to_cart_fragments', 10, 1);

Note, that there is a Stack Exchange extra for WordPress: https://wordpress.stackexchange.com/

  •  Tags:  
  • Related