Show/hide shipping methods based on a WooCommerce

2020-07-18 08:43发布

问题:

In WooCommerce, I have set different shipping methods, but one in particular must be exclusive for companies.

For this I am using the following code:

add_filter( 'woocommerce_package_rates', array( $this, 'package_rates' ), 10, 2 );

public function package_rates( $rates, $package ) {
    $company_rate_id = 'flat_rate:7';

    if(!empty(WC()->customer->get_billing_company())){
        $company_rates = $rates[ $company_rate_id ];
        $rates = array( $company_rate_id => $company_rates );
    }else{
        unset( $rates[ $company_rate_id ] );
    }

    return $rates;
}

The solution works, but only if the billing company already exist and is saved in the database. So if a customer updates this information on the checkout page, it doesn't work.

A possible solution would be to save this field live (billing_company).

I tried the following function:

add_filter( 'woocommerce_checkout_fields' , 'trigger_update_checkout_on_change' );
function trigger_update_checkout_on_change( $fields ) {

    $fields['billing']['billing_company']['class'][] = 'update_totals_on_change';

    return $fields;
}

This updates the shipping method, the problem is that again, the field is not saved in the database and the package_rates() function can not find it live.

回答1:

This is a bit more complicated than that… jQuery and Ajax code are required to allow showing/hiding shipping methods based on a checkout field user input.

The following code will enable show/hide pre defined shipping methods based on checkout billing company field:

// Conditionally show/hide shipping methods
add_filter( 'woocommerce_package_rates', 'shipping_package_rates_filter_callback', 100, 2 );
function shipping_package_rates_filter_callback( $rates, $package ) {
    // The defined rate id
    $company_rate_id = 'flat_rate:7';

    if( WC()->session->get('company' ) === '1' ) {
        $rates = array( $company_rate_id => $rates[ $company_rate_id ] );
    } else {
        unset( $rates[ $company_rate_id ] );
    }
    return $rates;
}

// function that gets the Ajax data
add_action( 'wp_ajax_get_customer_company', 'wc_get_customer_company' );
add_action( 'wp_ajax_nopriv_get_customer_company', 'wc_get_customer_company' );
function wc_get_customer_company() {
    if ( isset($_POST['company']) && ! empty($_POST['company']) ){
        WC()->session->set('company', '1' );
    } else {
        WC()->session->set('company', '0' );
    }
    die(); // (required)
}

// The Jquery Ajax script
add_action( 'wp_footer', 'custom_checkout_script' );
function custom_checkout_script() {
    if( WC()->session->__isset('company') ) 
        WC()->session->__unset('company');

    // Only on checkout when billing company is not defined
    if( is_checkout() && ! is_wc_endpoint_url() ):
    ?>
    <script type="text/javascript">
    jQuery( function($){
        if (typeof wc_checkout_params === 'undefined') 
            return false;

        var fieldId = 'input#billing_company';

        function companyTriggerAjax( company ){
            $.ajax({
                type: 'POST',
                url: wc_checkout_params.ajax_url,
                data: {
                    'action': 'get_customer_company',
                    'company': company,
                },
                success: function (result) {
                    // Trigger refresh checkout
                    $('body').trigger('update_checkout');
                }
            });
        }

        // On start
        if( $(fieldId).val() != '' ) {
            companyTriggerAjax( $(fieldId).val() );
        }

        // On change
        $(fieldId).change( function () {
            companyTriggerAjax( $(this).val() );
        });
    });
    </script>
    <?php
    endif;
}

// Enabling, disabling and refreshing session shipping methods data
add_action( 'woocommerce_checkout_update_order_review', 'refresh_shipping_methods', 10, 1 );
function refresh_shipping_methods( $post_data ){
    $bool = true;

    if ( WC()->session->get('company' ) === '1' )
        $bool = false;

    // Mandatory to make it work with shipping methods
    foreach ( WC()->cart->get_shipping_packages() as $package_key => $package ){
        WC()->session->set( 'shipping_for_package_' . $package_key, $bool );
    }
    WC()->cart->calculate_shipping();
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.


Related: Remove shipping cost if custom checkbox is checked in WooCommerce Checkout