WooCommerce – Conditional Ship to a Different Address Selection

October 31, 2017 (3 years ago)
WooCommerce, WordPress, JS, Functions

The scenario is this:

The site has multiple shipping methods (multiple client locations, and the option to ship to “Other”.)

I wanted to show the address panel if “Other” location was chosen, and hide the “Ship to Another Location”  option heading on the shipping page if a client location was chosen.

None of this was strictly necessary, but it makes for a smoother customer experience.

This went into my functions.php file.

/* added with my other enqueued scripts */
   wp_register_script( 'hideshipto', get_bloginfo( 'stylesheet_directory' ) . '/hide_ship_to.js', array( 'jquery' ) );


add_action( 'init', 'fb_ship_to_open' ); // opens the ship to for church dlievery or hides the ship to a different address for all others
function fb_ship_to_open () {
  global $woocommerce;
    if ( !is_admin() && WC()->session->get( 'chosen_shipping_methods' ) ) {
    $chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
    $chosen_shipping = $chosen_methods[0]; 
      if ('your_shipping_method_goes_here' == $chosen_shipping ) {
        add_filter( 'woocommerce_ship_to_different_address_checked', '__return_true' );
      } else {
        add_action( 'wp_enqueue_scripts', 'fb_load_ship_script' );
          function fb_load_ship_script() {
        wp_enqueue_script( 'hideshipto');
        }
      }
    }
  }

Then, this is the hide_ship_to.js script file. (uploaded to the theme directory)

jQuery( document ).ready(function($) {
    $('#ship-to-different-address').hide();
});

 

Skip to toolbar