logo
down
shadow

How do I find the shipping class id in WooCommerce?


How do I find the shipping class id in WooCommerce?

Content Index :

How do I find the shipping class id in WooCommerce?
Tag : php , By : user119985
Date : November 28 2020, 04:01 AM

seems to work fine To make it work with shipping class "Slugs" you will use WC_Product get_shipping_class() method instead this way:
add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_shipping_class', 10, 2 );
function hide_shipping_method_based_on_shipping_class( $rates, $package )
{
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // HERE define your shipping class SLUG
    $class_slug = 'large';

    // HERE define the shipping method to hide
    $method_key_id = 'flat_rate:7';

    // Checking in cart items
    foreach( WC()->cart->get_cart() as $cart_item ){
        // If we find the shipping class
        if( $cart_item['data']->get_shipping_class() == $class_slug ){
            unset($rates[$method_key_id]); // Remove the targeted method
            break; // Stop the loop
        }
    }
    return $rates;
}

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Unsetting shipping rates if a shipping class applies to all cart items in WooCommerce


Tag : php , By : Jorge Palacio
Date : March 29 2020, 07:55 AM
I hope this helps . Updated (corrected some errors)
You should try the following where I look for an item that has not the shipping class instead. Also I have revisited and compacted your code:
add_filter( 'woocommerce_package_rates',     'hide_table_shipping_for_shipping_class', 10, 2 );
function hide_table_shipping_for_shipping_class( $rates, $package ) {

    $targeted_class = 137; // <== Your targetted shipping class

    // Loop through cart items to find out if any hasn't the targetted shipping class
    foreach( WC()->cart->cart_contents as $key => $values ) {
        // IF One item is found without this shipping class
        if( $values[ 'data' ]->get_shipping_class_id() != $targeted_class ) {
            return $rates; // <== FOUND! We exit returning all Shipping rates
        } 
    }

    ## --------------------- REMOVING SHIPPING METHOD RATES IDS ---------------------- ##
    ##                 (when all cart items have the targeted shipping class)

    // All shipping instance IDs to be removed
    $instance_ids = array(
        '1', '2', '3', '4', '5', '6', '7', '8', '9', '10',
        '11', '12', '13', '14', '15', '16', '17', '18', '19', '20',
        '21', '22', '23', '24', '25', '26', '27', '28', '29', '30',
        '31', '32', '33', '34', '35', '36', '37', '38', '39', '40',
        '41', '42', '43', '44', '45', '46', '47', '48', '49', '50',
        '51', '52', '53', '54', '55', '56', '57', '58', '59', '60',
        '61', '62', '63', '64', '65', '66', '67', '68', '69', '70',
        '71', '72', '73', '74', '75', '76', '77', '78', '79', '80',
        '81', '82', '83', '84', '85', '86', '87', '88', '89', '90',
        '91', '92', '93', '94', '95', '96', '97', '98', '99', '100',
        '101', '102', '103',
    );

    // Loop: Unsetting each shipping method rate Ids
    foreach( $instance_ids as $id )
        unset( $rates['mh_wc_table_rate_plus_'.$id] );

    return $rates;
}

Hide and unhide a specific shipping methods based on shipping class in WooCommerce


Tag : php , By : Guy Kastenbaum
Date : March 29 2020, 07:55 AM
I hope this helps . i have a cart that has three method standard delivery(0-10kg), standard delivery(11-20kg) and next day delivery(0-20kg), my problem is when i a product with a frozen food shipping class to the cart the shipping method should only be the next day delivery and if there is now shipping class on the cart it only has the standard delivery, my problem is when a add the product with a shipping class and a products with no shipping class it will not go to the condition that i make. , Updated 2: There are many errors and mistakes in your codeā€¦
add_filter( 'woocommerce_package_rates', 'custom_hide_shipping_methods', 20, 2 );
function custom_hide_shipping_methods( $rates, $package ) {
    $targeted_class_id = 149;  // <== ID OF MY SHIPPING_CLASS
    $has_class = $has_no_class = false;

    // Loop through cart items
    foreach( WC()->cart->get_cart() as $cart_item  ) {
        $shipping_class = $cart_item['data']->get_shipping_class_id();
        # $weight = $cart_item['data']->get_weight();

        if( $shipping_class == $targeted_class_id ) 
            $has_class = true;
        elseif( empty( $shipping_class ) )
            $has_no_class = true;
    }
    // Unseting shipping methods
    if( $has_class ) 
    { // CASE 1 and 3
        unset( $rates['shipping_by_rules:16'] ); // standard delivery
        # wc_add_notice( sprintf( __( '1 | %s', 'woocommerce' ), $weight ), 'error' );
    }
    elseif( ! $has_class && $has_no_class )
    { // CASE 2
        unset( $rates['shipping_by_rules:15'] ); // next day delivery
        # wc_add_notice( sprintf( __( '2 | %s', 'woocommerce' ), $weight ), 'error' );
    }
    elseif( $has_class && $has_no_class ) // ==> Optional (You may not neeed it)
    { // CASE 3
        unset( $rates['shipping_by_rules:16'] ); // standard delivery
        # wc_add_notice( sprintf( __( '3 | %s', 'woocommerce' ), $weight ), 'error' );
    }
    return $rates;
}

Change shipping class based on cart items shipping class count in Woocommerce


Tag : php , By : DonMac
Date : March 29 2020, 07:55 AM
I wish this help you First you will need to make your shipping settings as in the below screen, for "Flat rate" shipping method and only one shipping class named "Mailbox" (setting the desired amounts for "Mailbox" or No shipping class):
// Updating cart item price
add_action( 'woocommerce_before_calculate_totals', 'change_change_shipping_class', 30, 1 );
function change_change_shipping_class( $cart ) {
    if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // HERE define your shipping class SLUG
    $mailbox_shipping_class = 'mailbox';

    $mailbox_count = 0;

    // 1st cart item Loop: Counting "mailbox" shipping classes cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        // Set the new price
        if( $cart_item['data']->get_shipping_class() == $mailbox_shipping_class ) {
            $mailbox_count += $cart_item['quantity'];
        }
    }

    // If there is more than one item we continue
    if( $mailbox_count <= 1 )
        return; // Exit

    // 2nd cart item Loop: Reset the cart items with shipping class "mailbox"
    foreach ( $cart->get_cart() as $cart_item ) {
        if(  $cart_item['data']->get_shipping_class() == $mailbox_shipping_class ){
            $cart_item['data']->set_shipping_class_id('0');
        }
    }
}

Conditional free shipping based on shipping class and minimal amount in Woocommerce


Tag : php , By : arcadian
Date : March 29 2020, 07:55 AM
should help you out Updated: To make it work first you will need:
- To add a "Free" shipping class (first),
add_filter('woocommerce_package_rates', 'conditional_free_shipping', 10, 2);
function conditional_free_shipping( $rates, $package ){
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return $rates;

    ## -- Your settings bellow -- ##

    $shipping_class  = 'free'; // "Free" shipping class products
    $min_free_amount = 200;    // Minimal Free shipping amount for normal products

    ## -- -- -- -- -- -- -- -- -- ##

    $has_free = false; // Initializing
    $products_total = 0; // Initializing

    // Loop through cart items
    foreach( $package['contents'] as $cart_item ) {
        if( $cart_item['data']->get_shipping_class() == $shipping_class ) {
            $has_free = true;
        } else {
            // Get the total purchased amount for normal product
            $products_total += $cart_item['line_total'] + $cart_item['line_tax'];
        }
    }

    foreach ( $rates as $rate_key => $rate ){
        // 1. Only Free shipping products in cart OR both products kind in cart
        if( $has_free ) {
            if( 'flat_rate' === $rate->method_id )
                unset( $rates[$rate_key] ); // Remove flat rate
        }
        // 2. Only normal products in cart
        else {
            // A. If it's under the min amount
            if( 'free_shipping' === $rate->method_id && $products_total < $min_free_amount )
                unset( $rates[$rate_key] ); // Remove Free shipping
            // B. When min amount is reached
            elseif( 'flat_rate' === $rate->method_id && $products_total >= $min_free_amount )
                unset( $rates[$rate_key] ); // Remove flat rate
        }
    }
    return $rates;
}

Custom calculated shipping costs based on shipping class in WooCommerce


Tag : php , By : baylisscg
Date : March 29 2020, 07:55 AM
Hope this helps After updating Woocommerce to the latest version 3.5.7 last night, the checkout is freezing if country is switched from US to Canada on the checkout page. If we go back to the cart page, an error is shown. The error details are at the end of this question. What could be causing this? I have also copied the piece of code below that's leading to this error. Specifically, the line $label = $method->get_label();, but I don't see any issues with this. , Update #1: (Based on your 2nd Edit)
Try the following instead:
add_filter( 'woocommerce_package_rates', 'custom_shipping_rates_based_on_shipping_class', 11, 2 );
function custom_shipping_rates_based_on_shipping_class( $rates, $package ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // HERE define your shipping class to find
    $class = array(206);

    // HERE define the shipping method to change rates for
    $shipping_rate_ids = array('flat_rate:5', 'flat_rate:6')

    // Initialising
    $found = false;
    $item_price = $item_qty = $rush_fee = $item_total = 0;

    // Loop through cart items
    foreach( $package['contents'] as $cart_item_key => $cart_item ) {
        $item_shipping_class_id = $cart_item['data']->get_shipping_class_id();

        if( in_array( $item_shipping_class_id, $class ) ){
            $item_price += $cart_item['data']->get_price(); // Sum line item prices that have target shipping class
            $item_qty += $cart_item['quantity']; // Sum line item prices that have target shipping class
            $item_total = $item_price * $item_qty;
            $rush_fee = $item_total * 0.2;
            $found = true;  // Target shipping class found
        } 
    }

    if( $found ) {
        // Loop through shipping rates
        foreach( $rates as $rate_key => $rate ) {
            if( in_array($rate_key, $shipping_rate_ids) ) {
                if( $item_total > 0 && $item_total < 200 ) {
                    if($rush_fee < 25) {
                        $rates[$rate_key]->cost = 25 + 18.99;
                    } else {
                        $rates[$rate_key]->cost = $rush_fee + 18.99;
                    }
                }
                elseif ( $item_total > 200 ) {
                    if($rush_fee < 25) {
                        $rates[$rate_key]->cost = 25;
                    } else {
                        $rates[$rate_key]->cost = $rush_fee;
                    }
                }
            }
        }
    }
    return $rates;
}
$label = $method->get_label();
$label = $method->label; 
Related Posts Related QUESTIONS :
  • Error in validating message of no votes PHP
  • Symfony site on Azure with ClearDB connection
  • Woocommerce upsell with checkboxes
  • How to login/logout with Hybridauth 3?
  • Convert INT number in PHP
  • php/mysql. selecting 2 common fields in 2 tables
  • Expand an string based on values in an array in PHP
  • When you absolutely have to manually escape SQL in CakePHP 3.4.7
  • Htaccess redirecting wrong page
  • Laravel Optional WHERE clause
  • PHP unpack overlfow variable memory limit
  • How to check the URL's structure using PHP preg_match?
  • PHP preg_replace - text will not be recognized
  • Show image from other domain without showing the domain name - PHP
  • How to run and watch local server at the same time?
  • Access form request from Observer laravel
  • single quote problem with preg_replace_callback
  • How to Create A Unique URL for each product enquiry form for Google Analytics Tracking
  • Laravel email configuration: what am I missing?
  • Assign indexed array values to multidimensional array?
  • Custom WordPress stylesheet not loading
  • Data attribute only returning first value
  • How to list all roles with Permissions,in spatie permission Package?
  • How to achieve this number pattern with n input
  • How to iterate array inside array data in laravel ,output are given below
  • To get output of movie with its genre
  • Extracting some data from a JS object literal string in PHP using Regex
  • axios and vuex are deleting wrong index in array
  • Setting empty CURLOPT_POSTFIELDS
  • Laravel 5.8 use subdomain as API endpoint beside domain.com/api
  • Error while add data in database SQL Server 2016
  • Does PhpStorm allow to skip PHPDoc tags when type hints is declared?
  • html classes are changed to Attributes
  • Using json to import multidimensional data
  • passing data from the view to the controller, where the data comes from another controller
  • How to extract integer and decimal numbers in PHP string correctly?
  • Parsing Sub-Object from an XML Feed with objects
  • Getting error "Unknown column 'text' in 'field list'"
  • How to properly get onedrive access token via php and curl
  • How to add spell check to a php function
  • Is it posible to create css rules with php?
  • Pretty URL with $_GET method
  • Wordpress always load same page - index.php
  • Find value in array and return with new from different array
  • PHP multiple file upload with different keys
  • Can't modify times one a time without weird errors
  • Get size of scraped image with domcrawler (Goutte)
  • Laravel - Ordering a collection of models
  • PHP Fatal error: Uncaught Error: Call to a member function setFetchMode() on boolean
  • Strict Standards: Only variables should be passed by reference in /main_dir/sub_dir/backup.php
  • Uncaught Google_Exception: (update) unknown parameter: 'copyRequiresWriterPermission'
  • Laravel 5 form does not redirect with old input
  • How to get values greater than or equal to in Mysql database sql when its a value like 1:00 PM?
  • PHP datediff overday issue
  • Masking an auto incrementing primary key
  • How to grab a String BEFORE a certain word
  • ZF2 Routing Multiple Controllers based on route constraints
  • How to deregister/dequeue jquery.sticky.js in Elementor (Pro)?
  • How to fix errors counting words in text plain with PHP?
  • How to get View data in Laravel in custom helper or directive
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com