vapvarun icon

Prohibit a specific product to specific states

vapvarun | PRO | 10/05/19 06:33:22 PM UTC | 0 ⭐ | 848 👁️ | Never ⏰ | []
PHP |

990 B

|

None

|

0 👍

/

0 👎

/**
 * Prohibit a specific product to specific states
 */
function custom_add_validation_rules_products() {
 
    if ( ! isset( WC()->cart ) ) {
        return;
    }
 
    $shipping_country    = WC()->customer->get_shipping_country();
    $shipping_state      = WC()->customer->get_shipping_state();
    $cart_contents       = WC()->cart->cart_contents;
    $cart_product_ids    = wp_list_pluck( $cart_contents, 'product_id' );
    $prohibited_products = array( 188, 189 ); // Add prohibited product IDs here
    $prohibited_states   = array( 'HI', 'AK' ); // Add prohibited states here
 
    // Invalidate when trying to ship a specific products to prohibited states
    if ( 'US' == $shipping_country && in_array( $shipping_state, $prohibited_states ) && array_intersect( $prohibited_products, $cart_product_ids ) ) {
        wc_add_notice( __( 'There are some products in your cart that cannot be shipped to your location.' ), 'error' );
    }
 
}
add_action( 'woocommerce_checkout_process', 'custom_add_validation_rules_products' );

Comments