Hide multiple shipping methods based on product IDs in WooCommerce - php

I want to hide a set of shipping methods if a set of products are selected on WooCommerce
I think I'm almost there but I am getting an error on the unset( $rates[$method_ids] ) line.
Here's what I've got so far:
add_filter( 'woocommerce_package_rates', 'specific_products_shipping_methods_hide_many', 10, 2 );
function specific_products_shipping_methods_hide_many( $rates, $package ) {
$product_ids = array( 240555 ); // HERE set the product IDs in the array
$method_ids = array( 'flat_rate:7', 'flat_rate:13', 'flat_rate:26', 'flat_rate:27', 'local_pickup:24' ) ; // HERE set the shipping method IDs
$found = false;
// Loop through cart items Checking for defined product IDs
foreach( $package['contents'] as $cart_item ) {
if ( in_array( $cart_item['product_id'], $product_ids ) ){
$found = true;
break;
}
}
if ( $found )
unset( $rates[$method_ids] );
return $rates;
}
Any advice?

You are close, but you need to loop through $rates and if it occurs $rate_id, you can unset it
So you get:
function filter_woocommerce_package_rates( $rates, $package ) {
// Set the product IDs in the array
$product_ids = array( 240555, 30 );
// Set the rate IDs in the array
$rate_ids = array( 'flat_rate:7', 'flat_rate:13', 'flat_rate:26', 'flat_rate:27', 'local_pickup:24', 'local_pickup:1', 'free_shipping:2' );
// Initialize
$found = false;
// Loop through cart items checking for defined product IDs
foreach( $package['contents'] as $cart_item ) {
// Checks if a value exists in an array
if ( in_array( $cart_item['product_id'], $product_ids ) ) {
$found = true;
break;
}
}
// True
if ( $found ) {
// Loop trough
foreach ( $rates as $rate_id => $rate ) {
// Checks if a value exists in an array
if ( in_array( $rate_id, $rate_ids ) ) {
unset( $rates[$rate_id] );
}
}
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );

Related

Hide multiple shipping methods for specific products in Woocommerce [duplicate]

I want to hide a set of shipping methods if a set of products are selected on WooCommerce
I think I'm almost there but I am getting an error on the unset( $rates[$method_ids] ) line.
Here's what I've got so far:
add_filter( 'woocommerce_package_rates', 'specific_products_shipping_methods_hide_many', 10, 2 );
function specific_products_shipping_methods_hide_many( $rates, $package ) {
$product_ids = array( 240555 ); // HERE set the product IDs in the array
$method_ids = array( 'flat_rate:7', 'flat_rate:13', 'flat_rate:26', 'flat_rate:27', 'local_pickup:24' ) ; // HERE set the shipping method IDs
$found = false;
// Loop through cart items Checking for defined product IDs
foreach( $package['contents'] as $cart_item ) {
if ( in_array( $cart_item['product_id'], $product_ids ) ){
$found = true;
break;
}
}
if ( $found )
unset( $rates[$method_ids] );
return $rates;
}
Any advice?
You are close, but you need to loop through $rates and if it occurs $rate_id, you can unset it
So you get:
function filter_woocommerce_package_rates( $rates, $package ) {
// Set the product IDs in the array
$product_ids = array( 240555, 30 );
// Set the rate IDs in the array
$rate_ids = array( 'flat_rate:7', 'flat_rate:13', 'flat_rate:26', 'flat_rate:27', 'local_pickup:24', 'local_pickup:1', 'free_shipping:2' );
// Initialize
$found = false;
// Loop through cart items checking for defined product IDs
foreach( $package['contents'] as $cart_item ) {
// Checks if a value exists in an array
if ( in_array( $cart_item['product_id'], $product_ids ) ) {
$found = true;
break;
}
}
// True
if ( $found ) {
// Loop trough
foreach ( $rates as $rate_id => $rate ) {
// Checks if a value exists in an array
if ( in_array( $rate_id, $rate_ids ) ) {
unset( $rates[$rate_id] );
}
}
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );

woocommerce - check if cart cointains 2 specific categories

currently i can check if the cart contains categories (or a specific category) with this function..
function check_the_cart_for_categories() {
// holds checks for all products in cart to see if they're in our category
$category_checks = array();
// check each cart item for our category
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
$product_in_cat = false;
if ( has_term( array('clothing', 'shoes','hats'), 'product_cat', $product->id ) ) {
#if ( has_term( 'clothing', 'product_cat', $product->id ) ) { //or for one
$product_in_cat = true;
}
array_push( $category_checks, $product_in_cat );
}
// if all items are in this category, do something
if ( ! in_array( false, $category_checks, true ) AND $ship_check ) {
echo "showmessage";
}
}
add_action( 'woocommerce_proceed_to_checkout' , 'check_the_cart_for_categories');
add_action( 'woocommerce_review_order_before_submit' , 'check_the_cart_for_categories');
but i want to check if the cart contains SHOES and HATS! (not any of them) ?
thank you!
Your code can be done but need to do fix some bugs. check my below code.
function check_the_cart_for_categories() {
// holds checks for all products in cart to see if they're in our category
$product_in_cat = false;
// check each cart item for our category
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product_id = $cart_item['product_id'];
if ( has_term( 'shoes', 'product_cat', $product_id ) && has_term( 'hats', 'product_cat', $product_id ) ) {
$product_in_cat = true;
}
break;
}
// if all items are in this category, do something
if ( $product_in_cat ) {
echo "showmessage";
}
}
add_action( 'woocommerce_proceed_to_checkout', 'check_the_cart_for_categories' );
add_action( 'woocommerce_review_order_before_submit', 'check_the_cart_for_categories' );
UPDATE as per OP request. ( check both categories in cart )
function check_the_cart_for_categories() {
// Categories in a coma separated array
$must_categories = array('shoes','hats');
$fee_amount = 0;
$product_cat = array();
// Loop through cart items
foreach( $cart->get_cart() as $cart_item ){
$terms = get_the_terms( $cart_item['product_id'], 'product_cat' );
foreach ($terms as $term) {
$product_cat[] = $term->slug;
}
}
foreach ( $must_categories as $key => $must_cat ) {
if( in_array($must_cat, $product_cat) ){
$product_in_cat = true;
}else{
$product_in_cat = false;
break;
}
}
// if all items are in this category, do something
if ( $product_in_cat ) {
echo "showmessage";
}
}
add_action( 'woocommerce_proceed_to_checkout', 'check_the_cart_for_categories' );
add_action( 'woocommerce_review_order_before_submit', 'check_the_cart_for_categories' );

Thank you page redirection for specific product ID in WooCommerce Order items

One of my products requires a specific thank you page.
Here's the code I have. The Product ID is 1813 and the category is gimnasio-mental. I don't really need, nor want to include the category in this code, so if it can be simplified, even better!
add_action( 'template_redirect', 'wc_custom_redirect_after_purchase' );
function wc_custom_redirect_after_purchase() {
if ( ! is_wc_endpoint_url( 'order-received' ) ) return;
// Define the product IDs in this array
$product_ids = array( 1813 ); // or an empty array if not used
// Define the product categories (can be IDs, slugs or names)
$product_categories = array( 'gimnasio-mental' ); // or an empty array if not used
$redirection = false;
global $wp;
$order_id = intval( str_replace( 'checkout/order-received/', '', $wp->request ) ); // Order ID
$order = wc_get_order( $order_id ); // Get an instance of the WC_Order Object
// Iterating through order items and finding targeted products
foreach( $order->get_items() as $item ){
if( in_array( $item->get_product_id(), $product_ids ) || has_term( $product_categories, 'product_cat', $item->get_product_id() ) ) {
$redirection = true;
break;
}
}
// Make the custom redirection when a targeted product has been found in the order
if( $redirection ){
wp_redirect( home_url( '/gracias-gimnasio-mental/' ) );
exit;
}
}
You could use the woocommerce_thankyou action hook against template_redirect
Explanation via comment tags added in the code
function action_woocommerce_thankyou( $order_id ) {
if( ! $order_id ) {
return;
}
// Instannce of the WC_Order Object
$order = wc_get_order( $order_id );
// Is a WC_Order
if ( is_a( $order, 'WC_Order' ) ) {
// False
$redirection = false;
// Loop through order items
foreach ( $order->get_items() as $item_key => $item ) {
// Product ID(s)
$product_ids = array( $item->get_product_id(), $item->get_variation_id() );
// Product ID in array
if ( in_array( 1813, $product_ids ) ) {
$redirection = true;
}
}
}
// Make the custom redirection when a targeted product has been found in the order
if ( $redirection ) {
wp_safe_redirect( home_url( '/gracias-gimnasio-mental/' ) );
exit;
}
}
add_action( 'woocommerce_thankyou', 'action_woocommerce_thankyou', 10, 1 );

Allow only Local Pickup for specific products outside specific Shipping Zone in WooCommerce

I have several products in the store, however one product (flammable) can only be shipped via a specific shipping company; Unfortunately that company can't reach the whole country. So in case the customer buys the flammable product and it's outside the coverage of the only company that can ship the product, he should not see any other shipping option except local pickup.
So far I have this code (courtesy of different StackOverFlow answers):
function filter_woocommerce_package_rates( $rates, $package ) {
// Shipping zone
//echo 'entrando';
$shipping_zone = wc_get_shipping_zone( $package );
$product_ids = array( 2267 ); // HERE set the product IDs in the array
$method_id = 'weight_based_shipping:38'; // HERE set the shipping method ID that I want to hide
$found = false;
// Get zone ID
$zone_id = $shipping_zone->get_id();
//echo $shipping_zone;
//echo $zone_id;
// NOT equal
if ( $zone_id != 8 ) {
// Unset a single rate/method for a specific product
foreach( $package['contents'] as $cart_item ) {
if ( in_array( $cart_item['product_id'], $product_ids ) ){
$found = true;
break;
}
}
if ( $found )
unset( $rates[$method_id] );
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );
however I don't know why is not working. Even the 'echo' is not working.
Updated - Try following instead (code is commented):
// SETTINGS BELOW: Custom function that handle your settings
function custom_shipping_settings() {
return array(
'product_ids' => array(2267), // Define the products that need to be in a separated shipping package (local pickup)
'allowed_zones_ids' => array(8), // Define the allowed zones IDs
);
}
// Splitting cart items into 2 shipping packages
add_filter( 'woocommerce_cart_shipping_packages', 'split_shipping_packages' );
function split_shipping_packages( $packages ) {
extract(custom_shipping_settings()); // Load and extract settings
$customer = WC()->customer;
$destination = array(
'country' => $customer->get_shipping_country(),
'state' => $customer->get_shipping_state(),
'postcode' => $customer->get_shipping_postcode(),
'city' => $customer->get_shipping_city(),
'address' => $customer->get_shipping_address(),
'address_2' => $customer->get_shipping_address_2()
);
$package_dest = array( 'destination' => $destination );
$zone = wc_get_shipping_zone( $package_dest );
if ( ! in_array( $zone->get_id(), $allowed_zones_ids ) ) {
// Reset packages and initialize variables
$packages = $splitted_cart_items = array();
// Loop through cart items
foreach ( WC()->cart->get_cart() as $item_key => $item ) {
if ( is_a($item['data'], 'WC_Product') && $item['data']->needs_shipping() ) {
if ( ! array_intersect( array($item['product_id'], $item['variation_id']), $product_ids ) ) {
$splitted_cart_items[0][$item_key] = $item; // Regular items
} else {
$splitted_cart_items[1][$item_key] = $item; // Special separated items
}
}
}
if ( count($splitted_cart_items) < 2 )
return $packages;
// Loop through spitted cart items
foreach ( $splitted_cart_items as $key => $items ) {
// Set each cart items group in a shipping package
$packages[$key] = array(
'contents' => $items,
'contents_cost' => array_sum( wp_list_pluck( $items, 'line_total' ) ),
'applied_coupons' => WC()->cart->get_applied_coupons(),
'user' => array( 'ID' => get_current_user_id() ),
'destination' => $destination,
);
}
}
return $packages;
}
// Force local pickup for specific splitted shipping package (for the defined products)
add_filter( 'woocommerce_package_rates', 'filter_wc_package_rates', 10, 2 );
function filter_wc_package_rates( $rates, $package ) {
extract(custom_shipping_settings()); // Load and extract settings
$zone = wc_get_shipping_zone( $package ); // Get current shipping zone
$found = false;
// For all others shipping zones than allowed zones
if ( ! in_array( $zone->get_id(), $allowed_zones_ids ) ) {
// Loop through cart items for current shipping package
foreach( $package['contents'] as $item ) {
// Look for defined specific product Ids
if ( array_intersect( array($item['product_id'], $item['variation_id']), $product_ids ) ) {
$found = true; // Flag as found
break; // Stop the loop
}
}
// If any defined product is in cart
if ( $found ) {
// Loop through shipping rates
foreach ( $rates as $rate_key => $rate ) {
// Hide all shipping methods keeping "Local pickup"
if ( 'local_pickup' !== $rate->method_id ) {
unset( $rates[$rate_key] );
}
}
}
}
return $rates;
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Refresh the shipping caches:
This code is already saved on your functions.php file.
In a shipping zone settings, disable / save any shipping method, then enable back / save.
You are done and you can test it.

Hide shipping methods by product category and if not

I am trying to put together a function to hide a shipping method if there is a finished product category in the cart and if that category is not in the cart then hide another one.
This is the function that I have been able to put together, but it doesn't work. Can you help me please?
function product_category_find_id_in_cart() {
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ){
if ( has_term( 'hangers', 'product_cat', $cart_item['product_id'] ) ) {
unset( $rates['free_shipping1'] );
}
else {
unset( $rates['flat_rate:6'] );
}
return $rates;
}
}
I need it to also work for various shipping methods, not just to hide one. Thank you!
Thanks to # 7uc1f3r I have a new code that hides the shipping method if the product belongs to a category, but I need that if the product does not belong to that category other shipping methods are hidden. This would be the new formula, thanks to #LoicTheAztec:
add_filter( 'woocommerce_package_rates', 'specific_products_shipping_methods', 10, 2 );
function specific_products_shipping_methods( $rates, $package ) {
// HERE set the product category in the array (ID, slug or name)
$terms = array( 'hangers' );
$taxonomy = 'product_cat';
// HERE set the shipping methods to be removed (like "fat_rate:5")
$method_instances_ids = array('1');
$found = false;
// Loop through cart items checking for defined product IDs
foreach( $package['contents'] as $cart_item ) {
if ( has_term( $terms, $taxonomy, $cart_item['product_id'] ) ){
$found = true;
break;
}
}
if ( ! $found ) return $rates; // If not found we exit
// Loop through your active shipping methods
foreach( $rates as $rate_id => $rate ) {
// Remove all other shipping methods other than your defined shipping method
if ( in_array( $rate_id, $method_instances_ids ) ){
unset( $rates[$rate_id] );
}
}
return $rates;
}
I found it!!
add_filter( 'woocommerce_package_rates', 'specific_products_shipping_methods', 10, 2 );
function specific_products_shipping_methods( $rates, $package ) {
// HERE set the product category in the array (ID, slug or name)
$terms = array( 'hangers' );
$taxonomy = 'product_cat';
// HERE set the shipping methods to be removed (like "fat_rate:5")
$method_instances_ids = array('flat_rate:12','flat_rate:13','flat_rate:14');
$found = false;
// Loop through cart items checking for defined product IDs
foreach( $package['contents'] as $cart_item ) {
if ( has_term( $terms, $taxonomy, $cart_item['product_id'] ) ){
$found = true;
break;
}
}
if ( ! $found ) { unset( $rates['flat_rate:6'],$rates['flat_rate:7'],$rates['flat_rate:8'],$rates['flat_rate:9'],$rates['flat_rate:10'],$rates['flat_rate:11'] ); return $rates;} // If not found we exit
else {
// Loop through your active shipping methods
foreach( $rates as $rate_id => $rate ) {
// Remove all other shipping methods other than your defined shipping method
if ( in_array( $rate_id, $method_instances_ids ) ){
unset( $rates[$rate_id] );
}
}
return $rates;
}}

Categories