Getting billing country in WooCommerce fragment refresh - woocommerce

In WooCommerce I use the following JS Code, to trigger the refresh fragment, when changing billing country:
jQuery(document).ready(function(){
// Change Billing Country: Refresh WC Fragment
jQuery(document.body).on('change', 'select[name=billing_country]', function(){
jQuery(document.body).trigger('wc_fragment_refresh');
});
});
This works perfectly and runs the following PHP function:
function wc_refresh_mini_cart_billing_country($fragments){
ob_start();
// Hidden code, works perfectly...
// Get and output billing country
$billing_country = WC()->customer->get_billing_country();
echo $billing_country;
// Update fragment
$fragments['#your-billing-country'] = ob_get_clean();
return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'wc_refresh_mini_cart_billing_country');
Now this works, BUT I always get the old billing country, not the current one. For example: I am on the checkout page and country is set to Germany. If I change that to France, the above code will display "DE" (for Germany), after changing it again to Italy, the above code will display "FR" (for France). So it always takes the last chosen country, not the current selected.
What am I missing?

Please modify your jQuery code and replace it with below code:
jQuery(document.body).on('change', 'select[name=billing_country]', function(){
setTimeout(function() {jQuery(document.body).trigger('wc_fragment_refresh');},1000);
});
Note:
Also, another solution is to use Ajax feature and run the "wc_frament_refresh" on ajax success.

Related

Can't correctly see Custom Events in GA4's Debug View

I'm working on a WordPress site and in order to have a custom tracking, I've tried a bunch of things but always encounter issues no matter what.
So it's an eShop (WooCommerce) and to start my tracking, I just try as a first step to add the Product Name as a custom parameter in my custom events.
Firstly, I tried to create a tag in GTM which uses a custom variable that gets its value from a data layer pushed in a JS file enqueued in my child theme.
Here's how I enqueued and populated the script, at the end of a function I called "tracking_process" :
wp_register_script('data_layer', get_stylesheet_directory_uri() . '/scripts/tracking.js', array('jquery'), null, false );
// "data" contains my product name
wp_add_inline_script('data_layer', 'var data = ' . wp_json_encode($data), 'after');
And here's the action :
add_action('wp_footer', 'tracking_process');
The script correctly loads on the page.
The product name is correctly sent to the script.
The data layer is correctly pushed as I can see in the Tag Assistant my product name in the data layer tab.
The issue is...
My data layer seems to be pushed after the tag is sent to GA4, resulting in my custom parameter always being empty in the custom event, in the Debug View.
add_action('wp_enqueue_scripts', 'tracking_process', 0);
I also tried something I found on another thread, to put the script at the beginning of the queue :
(I execute this line after "wp_register_script")
array_unshift(wp_scripts()->queue, 'data_layer');
All of this without any success, my data layer is always pushed after my tag is triggered.
So I tried another approach...
I tried to send my custom event directly from the JS file.
jQuery(document).ready( function() {
gtag('event', 'test_product', {
'product_name' : data.product_name,
});
});
Half of the time, the custom event doesn't show up in the Debug View, without any apparent reason.
When it does, it seems the "page_view" automatic event doesn't trigger.
And when I don't see the custom event, "page_view" shows up instead.
Note that in Tag Assistant, I always correctly see my custom event, so I really don't get why it doesn't in the Debug View.
The issue persists even after 48h (I've seen there can be some delay).
And that's a staging site, there's no traffic on it. The live site is brand new and has low traffic as well at the moment.
The complete PHP function :
function tracking_process(){
global $product;
if( is_product() ) {
if ( ! is_a( $product, 'WC_Product' ) ) {
$product = wc_get_product( get_the_id() );
}
$product_name = $product->get_name();
$data['product_name'] = $product_name;
}
wp_register_script('data_layer', get_stylesheet_directory_uri() . '/scripts/tracking.js', array('jquery'), null, false );
array_unshift(wp_scripts()->queue, 'data_layer');
wp_add_inline_script('data_layer', 'var data = ' . wp_json_encode($data), 'after');
};
add_action('wp_enqueue_scripts', 'tracking_process', 0);
I searched a lot online but found nothing that fixed this issue, and even tried with ChatGPT by giving him precise details but nothing worked so far.
Also note that I already created the custom dimensions in GA4 so it recognizes my custom parameters, and that I don't get any error in the console.
Anyone having an idea of how I can fix this issue ?
Thanks in advance !

Refreshing mini-cart when following the link to checkout/order-received

Auto-updating the cart on the site using this action works well:
add_action( 'wp_footer', 'cart_update_qty_script' );
function cart_update_qty_script() {
if (is_cart()) :
?>
<script>
jQuery('div.woocommerce').on('change', '.qty', function(){
jQuery("[name='update_cart']").removeAttr("disabled").trigger("click");
});
</script>
<?php
endif;
}
The cart and the ordering page have been united into one (just "cart")
When switching from the "cart" page to the "checkout/order-received" page, the mini-cart does not become zero. Only updating manually makes the mini-basket null. (Basically, you have already finished with the order, getting thanked for your order, yet the miniature is still not refreshed.)
Is there any way to fix it? I use WooCommerce 6.5.1. Payment is disabled on the site.

Trigger event after change of variation WooCommerce

I have a price block for every single product page in the WooCommerce project. Like Cash Price, COD Price, PayPal, Stripe, etc.
Here what I want is to change this pricing based on the selected variation.
Ex: I have capacities like 32GB, 64GB, 128GB. So, change this price block based on the selected variation.
Therefore I tried to add an action where I can trigger the event when variations were added. But I can't see that action is working. This is my action code to trigger when variation is selected and price changes. But I can't see this alert in firing.
function change_pricing_block() {
?>
<script>
$( ".variations_form" ).on( "woocommerce_variation_select_change", function () {
alert('variation');
});
</script>
<?php
}
add_action( 'wp_footer', 'change_pricing_block' );
Can anybody help me with this?
Thanks in advance

javascript woocommerce form validation on add to cart buton before adding to cart

I have a custom page that displays a product with variations, a custom field and add to cart button.
I need to trigger some validation in javascript when the add to cart button is clicked, but if the form doesn't validate, then add to cart can't be performed.
I'd like to know if it's possible to achieve.
First I tried to do as explained here :
WooCommerce add to cart validation: prevent add to cart
It's working great and I'd like to be able to use this code but for me it can't be because :
- I'm using a custom page and not the usual woocommerce product page
- This means that after validation, I'm redirected to the standard woocommerce page which is blank
That's why I really need to use Javascript to perform this:
- javascript or jquery function triggered on the add to cart click
- then the function checks it everything is ok
- if yes, then product can be added to cart
- if no, an alert is displayed and the user remains on the same page, nothing added to cart.
I tried to be as clear as possible.
Hoping I can get some help.
Thanks a lot.
Please try this way:
function so_validate_add_cart_item( $passed, $product_id, $quantity, $variation_id = '', $variations= '' ) {
<script>
jQuery(function($){
jQuery(document).on('click', '.single_add_to_cart_button', function (e) {
e.preventDefault();
// your validation here
});
});
</script>
}
add_filter( 'woocommerce_add_to_cart_validation', 'so_validate_add_cart_item', 10, 5 );

How to reset all fields when adding to WooCommerce Cart

I'm developing a site with WooCommerce and have used the plugin Product Addons to add extra fields of text to the item being purchased (name, email address, phone number, etc). When someone clicks on "Add to Cart", the site currently adds the product to the cart, refreshes the page, but the previous data remains in the fields. I want to reset all the fields and make them empty after the product has been added.
I tried using this function:
( function($) {
$( document.body ).on( 'added_to_cart', function() {
$('input').val(''); }
);
} ) ( jQuery );
Any suggestions?
If the page literally refreshes itself then it is not at all standard. It was done just to update the mini cart at the top right corner of your menu and products are being added through ajax. In this case you can't empty all fields on some event because the page is being refreshed, what you have to do is write you code under document.ready function, perform $.each function on the common class or input and empty the input fields.
Try this action hook in your plugin or theme functions.php file
add_filter( 'woocommerce_checkout_get_value', 'misha_clear_checkout_fields_vals' );
function misha_clear_checkout_fields_vals($input){
return '';
}

Resources