Woocommerce set and unset shipping based on Shipping Address Checked - php

UPDATED QUESTION AFTER Scriptonomy ANSWER BELOW
I have a woocommerce site in which I have a few different shipping options. I need to hide and show these shipping options based on the "Ship to different address button being checked"
//remove local pickup
function ddc_hide_shipping( $rates, $package ) {
unset( $rates['local_pickup'] );
return $rates;
}
//check if needs shipping address so we can unset local pickup
function ddc_update_shipping_options($instance) {
parse_str(html_entity_decode($instance), $postData);
if ( #$postData['ship_to_different_address'] ) {
add_filter('woocommerce_package_rates', 'ddc_hide_shipping');
}
}
add_action('woocommerce_checkout_update_order_review', 'ddc_update_shipping_options');
Using the above code that got from help from Scriptonomy I am getting closer. The problem I am having as this doesn't seem to work when the user checks and un checks the ship to different billing address. This only works for me on first page load, not on every ajax call to update the order review area.
Thank you.

WC()->cart->needs_shipping_address() is based on store settings and item settings...so not ideal in this case, it will trigger every time in most cases.
Use the $instance data instead which is a url encoded string.
Decode and parse the string then test for the ship_to_different_address option
Suppress invalid array index errors when the option is not selected
Here's your solution:
parse_str(html_entity_decode($instance), $postData);
if ( #$postData['ship_to_different_address'] ) {
add_filter( 'woocommerce_package_rates', 'ddc_hide_shipping', 10, 2 );
}
Put this in your action hook.

Related

Hide specific shipping method depending on day time in WooCommerce

I'm looking to create a PHP code snippet that I would add to my functions.php file but I'm not sure how to proceed.
Someone asked the same question 2 years ago (Woocommerce - disable certain shipping methods based on time of day) but finally opted for a plugin that does that. I already use add-ons for detailed delivery options and I don't want to change or add another one just for this simple function if something can be done easily with php.
So I'm looking to disable a shipping method if the client order after 11AM (website time zone).
So I have this code for now :
if (date('H') > 11) {
$shippingmethod1.disable();
}
Can someone give me the proper code to make it work?
This is quiet simple using woocommerce_package_rates filter hook.
Now you need to find out what is the shipping rate Id reference that you need to target. For that you will inspect the desired shipping method radio button (<input> field) with your browser tools to get value as shown below:
Once you get it you will set that in the code below:
add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_time', 10, 2 );
function hide_shipping_method_based_on_time( $rates, $package )
{
// Set your default time zone (http://php.net/manual/en/timezones.php)
date_default_timezone_set('Europe/London');
// Here set your shipping rate Id
$shipping_rate_id = 'local_pickup:13';
// When this shipping method is available and after 11 AM
if ( array_key_exists( $shipping_rate_id, $rates ) && date('H') > 11 ) {
unset($rates[$shipping_rate_id]); // remove it
}
return $rates;
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Clearing shipping caches:
You will need to empty your cart, to clear cached shipping data
Or In shipping settings, you can disable / save any shipping method, then enable back / save.

Clear Woocommerce cart when sending multiple items by url

I need the Woocommerce cart to be cleaned in case I send more than four items to it via url.
I came up with this code, but it only cleans the cart if there are already five items in it.
//in functions.php
add_filter( 'woocommerce_add_to_cart_validation', 'remove_cart_item_before_add_to_cart', 20, 3 );
function remove_cart_item_before_add_to_cart( $passed, $product_id, $quantity ) {
if( WC()->cart->get_cart_contents_count() >= 5 )
WC()->cart->empty_cart();
return $passed;
}
Another problem is that, even the code above that is not useful to me, does not work if I add multiple courses via url, as in:
https://exemple.net/cart?fill_cart=100,101,102,103,104,105,106
That is, the code in functions.php only works from the website, and not by url.
All I need is clear the cart when sending more than 4 items by url.
I prefer a solution in PHP, but a JS solution will do. Thanks for who can help me.
I found a solution using the free plugin Cart links for WooCommerce, and making a few change in its code.
I will describe below what I did:
1) To start install the plugin, this will allow you to add products using the fill_cart parameter in url (as described in my question)
2) edit the plugin file soft79-cart-links-for-woocommerce.php found at: yoursite/wp-content/plugins/soft79-cart-links-for-woocommerce/
3) go to line 141 or find the declaration of the method fill_cart
Inside the fill_cart method uncomment (or add) the code to clean the cart:
public function fill_cart( $fill_string ) {
$original_notices = wc_get_notices();
wc_clear_notices();
////Clear the cart
//WC()->cart->empty_cart(); <-- uncomment here!
Save the file. Now any new items that arrive via url must clean the cart first.

Woocommerce add_filter to hide a flat rate method at certain times and not able to var_dump variable

Completely new to Woocommerce/wordpress here. On the cart page mydomain.local/cart What filter should I use to show/hide a flat rate shipping method at certain times. From admin I managed to add an extra flat rate method and named it "Next day". Now I would like to show that flat rate method only before 4PM. I tried in functions.php
add_filter( 'woocommerce_package_rates', 'custom_change_shipping', 10);
function custom_change_shipping($rates) {
var_dump($rates);
}
Nothing seems to change and also I cant seem to debug the $rates variable as nothing is outputted when var_dump($rates);. I tried it both anonymous and as an admin but nothing seems to work.
Thanks #LoicTheAztec for confirming whether I was using the right filter. My other problem was that I was not able to output var_dump on the /cart page.
I found out that I need to clear my "cart cache" by going to woocommerce->settings->shipping and in the region, disable then enable again and click on save changes.
By doing this I could see my output from var_dump.
Filter posted earlier by #LoicTheAztec (as requested by #robert)
add_filter( 'woocommerce_package_rates', 'custom_hide_shipping', 100 );
function custom_hide_shipping( $rates ) {
$current_time = date_i18n(('H'), current_time('timestamp')); //Uses Timezone Settings > General
$maximum_time = array (
'time' =>'16'); //4PM
if ($current_time >= $maximum['time']){
unset( $rates['flat_rate:X'] ); // change X to your rate id
}
return $rates;
}

Hide payment method based on product type in WooCommerce

In WoCommerce, I would like to disable particular payment methods and show particular payment methods for a subscription products in WooCommerce (and vice versa).
This is the closest thing we've found but doesn't do what I am expecting.
Yes, there are plugins that will do this but we want to achieve this without using another plugin and without making our stylesheet any more nightmarish than it already is.
Any help on this please?
Here is an example with a custom hooked function in woocommerce_available_payment_gateways filter hook, where I can disable payment gateways based on the cart items (product type):
add_filter('woocommerce_available_payment_gateways', 'conditional_payment_gateways', 10, 1);
function conditional_payment_gateways( $available_gateways ) {
// Not in backend (admin)
if( is_admin() )
return $available_gateways;
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$prod_variable = $prod_simple = $prod_subscription = false;
// Get the WC_Product object
$product = wc_get_product($cart_item['product_id']);
// Get the product types in cart (example)
if($product->is_type('simple')) $prod_simple = true;
if($product->is_type('variable')) $prod_variable = true;
if($product->is_type('subscription')) $prod_subscription = true;
}
// Remove Cash on delivery (cod) payment gateway for simple products
if($prod_simple)
unset($available_gateways['cod']); // unset 'cod'
// Remove Paypal (paypal) payment gateway for variable products
if($prod_variable)
unset($available_gateways['paypal']); // unset 'paypal'
// Remove Bank wire (Bacs) payment gateway for subscription products
if($prod_subscription)
unset($available_gateways['bacs']); // unset 'bacs'
return $available_gateways;
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
All code is tested on Woocommerce 3+ and works.
This is just an example to show you how things can work. You will have to adapt it
This code has been very useful to me, but there is an error in it that I had to fix: the line
$prod_variable = $prod_simple = $prod_subscription = false;
must be put OUTSIDE (before) the FOREACH otherwise it will reset the flag everytime a new item is executed. I my case, I needed to unset a specific payment method whenever a subscription product was on the cart. As it is, this code will work only if there is just a single subscription product. If I put another different item on cart, the flag will be turn to false again and the payment method will load. Putting the line outside the FOREACH will fix this problem.

WooCommerce: How to retain checkout info when client leaves then comes back?

Is there a simple way or a plugin to retain checkout information entered by the client after he/she leaves and comes back?
This plugin retains "fields information for customers when they navigate back and forth" however it has quite a lot of recent bad reviews so I don't think I'll use that for production. Any alternative suggestion?
---- Update ----
The code below is working, but only if data is submitted!
The only possible ways are javascript/jQuery form event detection on checkout fields and worpress Ajax:
Using ajax connected to some session transients function (as in code below).
Using (javascript) web Storage: localStorage, sessionStorage…
I have found some real interesting code in this thread that is using sessions transients to store checkout data.
// this function sets the checkout form data as session transients whenever the checkout page validates
function set_persitent_checkout ( $a ) {
$arr = array();
foreach ( $a as $key => $value )
if ( ! empty($value) )
$arr[$key] = $value;
WC()->session->set( 'form_data', $arr );
return $a;
}
add_action( 'woocommerce_after_checkout_validation', 'set_persitent_checkout' );
// this function hooks into woocommerce_checkout_get_value to substitute standard values with session values if present
function get_persistent_checkout ( $value, $index ) {
$data = WC()->session->get('form_data');
if ( ! $data || empty($data[$index]) )
return $value;
return is_bool($data[$index]) ? (int) $data[$index] : $data[$index];
}
add_filter( 'woocommerce_checkout_get_value', 'get_persistent_checkout', 10, 2 );
// This is a fix for the ship_to_different_address field which gets it value differently if there is no POST data on the checkout
function get_persitent_ship_to_different ( $value ) {
$data = WC()->session->get('form_data');
if ( ! $data || empty($data['ship_to_different_address']) )
return $value;
return is_bool($data['ship_to_different_address']) ? (int) $data['ship_to_different_address'] : $data['ship_to_different_address'];
}
add_action( 'woocommerce_ship_to_different_address_checked', 'get_persitent_ship_to_different' );
Add this code to the functions.php file located in your active child theme or theme.
Explanations from the author:
1. Save the form data:
The first function set_persitent_checkout hooks into woocommerce_after_checkout_validation.
Whenever that hook is fired, any current form data is saved as a WordPress transient via the WC_Session_Handler class (which was recently updated in version 2.5 to be a lot more efficient).
2. Check the saved data on reload:
Next we hook woocommerce_checkout_get_value with get_persitent_checkout. As the name suggests, here we check the session transients and return any matches for the current field if found.
3. Make ship_to_different_address work:
The only difficult was the ship_to_different_address field, which gets its value through a different method.
To get around this the final function was added. This works exactly the same as the previous function, but hooks into woocommerce_ship_to_different_address_checked.
There you have it. It would be nice if the data was saved after every field update on checkout, but the woocommerce_after_checkout_validation hook fires enough to capture the data at all the important points.
Functions.php snipped posted by LoicTheAztec didn't work for me.
I found this plugin which remembers everything I type or select in Woocommerce checkout, including shipping fields and my custom additions to the template:
Save Abandoned Carts – WooCommerce Live Checkout Field Capture
Account passwords, if creating during checkout, are naturally not remembered.

Categories