Clear WooCommerce cart on Currency Switcher change - php

I'm using the currency switcher WordPress plugin to change currencies on my website, I want the cart to be cleared once I change the currency. I've been trying for some time now, but can't figure out why it isn't working.
This is my source code in the theme functions.php file
function currency_change_action_callback() {
global $woocommerce;
$url_data=$_POST['url_data'];
$woocommerce->cart->empty_cart();
echo $url_data;
die();
}
add_action( 'wp_ajax_currency_change_action', 'currency_change_action_callback' );
add_action( 'wp_ajax_nopriv_currency_change_action', 'currency_change_action_callback' );
I've also tried creating a javascript file and calling it to my functions.php file. here are my source codes
app.js
$('#alg_currency_select').on('change', function () {
function Clearcart(d){
jQuery.post(
"http://localhost/epay/wp-admin/admin-ajax.php",
//ajaxurl,
{
"action": "clearcart",
"data": d.getAttribute("data-product")
},
function(){
window.location = d.getAttribute("data-href");
}
);
})};
functions.php
function load_javascript() {
wp_register_script('custom', get_template_directory_uri().'/app.js', 'jquery', 1, true);
wp_enqueue_script('custom');
}
add_action('wp_enqueue_scripts', 'load_javascript');
would greatly appreciate it if someone can help me solve the issue of why my cart isn't clearing. thanks.

There are some mistakes in your code and unnecessary things.
In the code below, the jQuery code is now located in a php function and enqueued in WordPress using the WooCommerce wc_enqueue_js() function.
// The jQuery Ajax enqueued code
add_action('template_redirect', 'currency_change_trigger_clear_cart_js' );
function currency_change_trigger_clear_cart_js() {
wc_enqueue_js( "jQuery( function($){
$(document.body).on('change', '#alg_currency_select', function() {
$.ajax({
url: '" . admin_url('/admin-ajax.php') . "',
type: 'POST',
data: {
'action': 'currency_change_clear_cart'
},
success: function(response) {
if( response == 'cleared' ) {
$(document.body).trigger('wc_fragment_refresh'); // Refresh cart
}
// console.log(response);
}
});
});
});" );
}
// Php AJAX receiver: Empty cart
add_action( 'wp_ajax_currency_change_clear_cart', 'currency_change_clear_cart' );
add_action( 'wp_ajax_nopriv_currency_change_clear_cart', 'currency_change_clear_cart' );
function currency_change_clear_cart() {
if( count(WC()->cart->get_cart()) > 0 ) {
WC()->cart->empty_cart();
echo 'cleared';
}
die();
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Related

Using wordpress action to modify div content

I'm trying to modify a div's content everytime when something is added to the woocommerce shopping cart. For this example the content is gonna be the current total cart value.
So first I created a simple plugin called "test-cart-value" which contains the following code:
<?php
function test_cart_value() {
echo "<div>" . WC()->cart->total . "</div>";
}
add_shortcode('test_cart_value_shortcode', 'test_cart_value');
This works fine, wherever I place the shortcode I get the current cart value after page load.
So, now I want this printed value to updated every time something is added to the cart, without reloading the page. The idea was to use the action hook woocommerce_cart_updated and call the function - so everytime something in the cart changes, the new cart value gets echoed:
function action_woocommerce_cart_updated() {
test_cart_value();
};
// add the action
add_action( 'woocommerce_cart_updated', 'action_woocommerce_cart_updated', 10, 0 );
The problem is, now I'm not able to dynamically add products to the shopping cart. Whenever I hit the "add to cart" button, the loading animation loads forever.
How to do this properly?
I was trying different approaches with Ajax and different Hooks, but so far nothing worked.
Any Ideas? Thanks in advance!
Edit:
So I tried this as my plugin code
function test_cart_value() {
echo "<div id='cart_test'>" . WC()->cart->total . "</div>";
}
add_shortcode('test_cart_value_shortcode', 'test_cart_value');
// define the actions for the two hooks created, first for logged in users and the next for logged out users
add_action("woocommerce_cart_updated", "cart_update");
// define the function to be fired for logged in users
function cart_update() {
$cart = WC()->cart->total;
$result['type'] = "success";
$result['new_cart'] = $cart;
$result = json_encode($result);
//if I uncomment the "die" function, the page won't load
// die();
}
// Fires after WordPress has finished loading, but before any headers are sent.
add_action( 'init', 'script_enqueuer' );
function script_enqueuer() {
// Register the JS file with a unique handle, file location, and an array of dependencies
wp_register_script( "test_script", plugin_dir_url(__FILE__).'test_script.js', array('jquery') );
// localize the script to your domain name, so that you can reference the url to admin-ajax.php file easily
wp_localize_script( 'test_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
// enqueue jQuery library and the script you registered above
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'test_script' );
}
And my test_script.js code:
jQuery(document).ready( function() {
jQuery(".ajax_add_to_cart").click( function(e) {
e.preventDefault();
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "cart_update"},
success: function(response) {
if(response.type == "success") {
jQuery("#cart_test").html(response.new_cart);
}
else {
alert("Your like could not be added");
}
}
});
});
});
So I thought that the cart_update() function should fire when I press the "ajax_add_to_cart" Button, but I get an error 400.
Any ideas?
Thanks!
made it work with woocommerce_add_to_cart_fragments.

WooCommerce: Get the post id in javascript code and pass it through ajax

I need help figuring out how to get the product id from the product page, to my function that opens a model box after a vimeo video ends.
inside that model box i need a variable with the product id. so i automatic can get the price of the product and insert the id inside a shortcode.
Hopefully someone can help, and feel free to ask, i will try to help if you need more information.
I have already tried the most common ideas, i could find.
global $product;
$id = $product->get_id();
or
global $post;
$id = $post->ID
or
global $product;
$id = $product->id;
I have tried in all the variations i could find.
if i use the first one, my function wont even work.
If i use the other 2, it only gives me a 0 as value.
// The javascript to call the function when video ends.
var iframe = document.querySelector("iframe");
var player = new Vimeo.Player(iframe);
player.on("ended", function() {
jQuery(document).ready(function($) {
var data = {
action: 'runThisPhpFunction',
};
jQuery.post(ajaxurl, data, function(popupfunction) {
$("#popup-box").html(popupfunction);
});
});
});
Next up is my function.
//Call Javascript video vimeo script to functions
function add_my_scripts() {
global $product;
$deps = array('jquery');
$in_footer = true;
wp_register_script( 'myjavascript', get_stylesheet_directory_uri() . '/js/myjavascript.js', array(), '1.0.0', true );
wp_enqueue_script( 'myjavascript', get_stylesheet_directory_uri() . '/js/myjavascript.js');
}
add_action( 'wp_enqueue_scripts', 'add_my_scripts' );
add_filter( 'widget_text', 'do_shortcode' );
add_action( 'wp_ajax_runThisPhpFunction', 'runThisPhpFunction' );
add_action( 'wp_ajax_nopriv_runThisPhpFunction', 'runThisPhpFunction' );
global $wpdb;
global $wp;
// THE FUNCTION WHERE I NEED THE ID FROM CURRENT PRODUCT PAGE AUTOMATIC
function runThisPhpFunction() {
global $product;
$product = wc_get_product();
$siteid = $product->ID;
//echo '<script>console.log($product);</script>';
echo '<script>document.getElementById("popup-box").classList.remove("hidden");</script>';
echo '<div class="modalheader">';
echo '<h3>Undskyld. Vi stoppede videoen!</h3>';
echo '</div>';
echo '<div class="modalcontent">';
echo $siteid, 'Men vi venter lige her, klar til at fortsætte når du har hentet Dankortet 😉';
echo '</div>';
}
As you are using javascript/jQuery/Ajax and as you need to get the product ID (which is the Post ID) in your Javascript code to pass it through Ajax to PHP, try the following revisited code instead:
add_action( 'wp_footer', 'custom_vimeo_player_script' );
function custom_vimeo_player_script() {
// Not in cart, checkout and my account pages
if( ! ( is_checkout() || is_cart() || is_account_page() ) ) :
?>
<script type="text/javascript">
jQuery(function($){
if (typeof wc_add_to_cart_params === 'undefined')
return false;
var iframe = document.querySelector("iframe"),
player = new Vimeo.Player(iframe);
player.on('ended', function(){
$.ajax({
type: 'POST',
url: wc_add_to_cart_params.ajax_url,
data: {
'action': 'enable_vimeo_popup_box',
'the_id': <?php echo get_the_id(); ?>,
},
success: function (result) {
// if popup-box has the class hidden
if( $("#popup-box").hasClass('hidden') && result ){
// remove the class hidden and add the html output
$("#popup-box").removeClass('hidden').html(result);
}
console.log(result);
},
});
});
});
</script>
<?php
endif;
}
// PHP: WordPress Ajax function triggered by Javascript
add_action( 'wp_ajax_enable_vimeo_popup_box', 'enable_vimeo_popup_box' );
add_action( 'wp_ajax_nopriv_enable_vimeo_popup_box', 'enable_vimeo_popup_box' );
function enable_vimeo_popup_box() {
if( isset($_POST['the_id']) ){
$post_id = (int) $_POST['the_id'];
echo '<div class="modalheader">
<h3>' . __("Undskyld. Vi stoppede videoen!") . '</h3>
</div><div class="modalcontent">' .
'<em>(post_id er ' . $post_id . ')</em> ' .
__("Men vi venter lige her, klar til at fortsætte når du har hentet Dankortet 😉") .
'</div>';
}
die();
}
Code goes in function.php file of your active child theme (or active theme). It should works.

Access WC() to get cart content in ajax callback

I'm trying to get woocommerce cart content in ajax callback function but it returns empty.
I've also tried using global $woocommerce variable that also returns the same result. I'm trying to get the cart content and convert all product to autoship feature. I'm using wooautoship plugin for that. however, main query is, how to get the cart details in ajax callback.
My Code is as follow:
add_action('wp_footer', 'woo_cart_autoship_js', 99);
function woo_cart_autoship_js(){
?>
<script type="text/javascript">
(function($){
$(document).on('click', '#convert-to-autoship', function(e){
e.preventDefault();
$.post( "<?php echo admin_url('admin-ajax.php'); ?>", { action: "convert-to-autoship" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
});
})(jQuery);
</script>
<?php
}
add_action( 'wp_ajax_convert-to-autoship', 'convert_to_autoship', 99 );
add_action( 'wp_ajax_nopriv_convert-to-autoship', 'convert_to_autoship', 99 );
function convert_to_autoship(){
print_r(WC()->cart->get_cart());
wp_die();
}

Exclude a dynamic value from cache with Wordpress Super Cache

I'm using the Super Cache plugin.
For some time I was looking for a solution, but without success. I need to disable the cache for one function in the file functions.php.
add_shortcode('custom_counter', 'example_shortcode');
function example_shortcode() {
// Get custom counter option value
$counter = get_option( 'wc-custom-counter' );
return '<span class="custom-counter">' . $counter . ' rub.</span>';
}
This is shortcode is used on the created custom page. It is necessary that the data output by this shortcode does not fall into the page cache.
Adapted from this old WSE thread, you will find below the complete way to make it working.
Here we display a spinner loading icon that will be replaced by the counter real non cached value through ajax. Javascript stays always active even in a cached page, so it can change anything needed on the page via Ajax or via any detected event. So there is no need to exclude anything in the plugin settings.
The replacement code:
// The shortcode
add_shortcode('custom_counter', 'customer_counter_shortcode');
function customer_counter_shortcode() {
// Start buffering
ob_start();
// Using woocommerce existing animated spinner gif icon
$loading_url = home_url( '/wp-content/plugins/woocommerce/assets/images/select2-spinner.gif' );
// Displaying a "Loading spinner icon + text to be replaced by Ajax value
echo '<span class="custom-counter">
<img id="loading-img" src="'.$loading_url.'" alt="Loading..." style="opacity:0.5; display:inline-block; vertical-align: middle;" />
<span style="opacity:0.5;"> ' . _("loading…") . '</span>
</span>';
?>
<script type="text/javascript">
jQuery( function($){
if (typeof woocommerce_params === 'undefined')
return false;
$.ajax({
type: 'POST',
url: woocommerce_params.ajax_url,
data: {
'action': 'custom_counter',
'custom-counter': true,
},
success: function (result) {
$('.custom-counter').text(result);
console.log('response: '+result); // just for testing | TO BE REMOVED
},
error: function(error){
console.log(error); // just for testing | TO BE REMOVED
}
});
});
</script>
<?php
return ob_get_clean(); // Return the buffered code
}
// The wordpress ajax hooked function (for logged in and non logged users)
add_action('wp_ajax_custom_counter', 'ajax_custom_counter');
add_action('wp_ajax_nopriv_custom_counter', 'ajax_custom_counter');
function ajax_custom_counter() {
if( isset($_POST['custom-counter']) && $_POST['custom-counter'] )
echo get_option( 'wc-custom-counter' ); // Get option value
exit();
}
Code goes in function.php file of your active child theme (or active theme). tested and works.
You cannot exclude a function from cache plugins. Instead you can exclude an URL (in WP Super Cache, go to 'Settings > WP Super Cache > Advanced' - 'Accepted Filenames & Rejected URIs' section).
So, call this function using AJAX instead calling directly and you can exclude the AJAX URL.
Here is the full code.
Add these in theme's functions.php:
add_action('wp_ajax_customer_counter', 'customer_counter_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_customer_counter', 'customer_counter_ajax_handler'); // wp_ajax_nopriv_{action}
function customer_counter_ajax_handler() {
// Get custom counter option value
$counter = get_option( 'wc-custom-counter' );
echo $counter . ' rub.';
}
Replace all your shortcodes [custom_counter] instances with <span class="customer_counter_shortcode"> </span>.
Add this script to theme's footer.php:
jQuery(function($){
$.ajax({
url : '<?php echo site_url(); ?>/wp-admin/admin-ajax.php', // AJAX handler
data : { action : 'customer_counter' },
type : 'POST',
success : function( $result ){
if( $result ) {
$('.customer_counter_shortcode').html($result);
}
}
});
});
You can then exclude the AJAX URL - /wp-admin/admin-ajax.php?action=customer_counter.

How to get wp_ajax to work with jQuery $.post

Straight from WP Codex: http://codex.wordpress.org/AJAX_in_Plugins
I have this in my functions.php:
add_action( 'admin_footer', 'my_action_javascript' );
function my_action_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
'action': 'my_action',
'whatever': 1234
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
</script>
<?php
}
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
die(); // this is required to return a proper result
}
And I don't get a response. I do get an alert saying 'Got this from the server: ', but no response. What gives?
Running your code on two separate wordpress installs from within a plugin file (plugin-name.php) and from within functions.php in my theme, it returns the proper value both times. There do not seem to be any errors in your code either.
Is this the only javascript you're including in the admin area?

Categories