write a snippet that adds a flat rate shipping fee if ship to another address is checked

WordPress AI Code Robot

Create WordPress code snippets for free without a developer!

{Name (First):7.3} requested the  following code from my WordPress AI Code Generator.

write a snippet that adds a flat rate shipping fee if ship to another address is checked

The robot generated the following code:

You can use the following WordPress code snippet to add a flat rate shipping fee if "Ship to another address" is checked:

“`php
function nm_add_flat_rate_shipping( $cart ) {
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_checkout() )
return;

// defining your flat rate
$flat_shipping_fee = 10;

// Change the postal code and country
$postcode = isset( $_POST['s_postcode'] ) ? sanitize_text_field( $_POST['s_postcode'] ) : '';
$country = isset( $_POST['s_country'] ) ? sanitize_text_field( $_POST['s_country'] ) : '';

// Shipping to another address
if ( $_POST['ship_to_different_address'] == '1' )
$cart->add_fee( __( 'Flat rate', 'your_theme_slug' ), $flat_shipping_fee );
}

add_action( 'woocommerce_cart_calculate_fees', 'nm_add_flat_rate_shipping' );
“`

Please replace 'your_theme_slug' with your actual theme slug and $flat_shipping_fee with the amount you want to add as flat rate shipping. Please ensure you have enabled the option to 'Collect Billing Address' from the WooCommerce settings page. Make sure to test the functionality on your site's checkout page before deploying it to live.

More
CODE SNIPPETS