Search code examples
phpwordpresswoocommercecheckoutshipping-method

Add customer postcode to specific shipping method on WooCommerce checkout


I am currently using the following code in the functions.php file.

add_action( 'woocommerce_after_shipping_rate', 'action_after_shipping_rate', 20, 2 );
function action_after_shipping_rate ( $method, $index ) {
    // Targeting checkout page only:
    if( is_cart() ) return; // Exit on cart page

    if( 'flat_rate:3' ) {
        echo __("<p>Delivery will take place tomorrow</br> morning between 8-12</p>");
        
    }
    
}

Now I would like to get the customer postcode, to then add it to my pre-existing code.

Someone who can help me with this?


Solution

  • You could use WC()->customer->get_shipping_postcode() to add the postcode

    So you get:

    function action_woocommerce_after_shipping_rate( $method, $index ) {    
        // Targeting checkout page only
        if ( is_cart() ) return;
    
        // Get shipping postcode
        $shipping_postcode = WC()->customer->get_shipping_postcode();
        
        // Compare
        if ( $method->get_id() === 'flat_rate:3' ) {
            // Output
            echo '<p>' . __( 'My text + zipcode = ', 'woocommerce') . $shipping_postcode . '</p>';      
        }
    }
    add_action( 'woocommerce_after_shipping_rate', 'action_woocommerce_after_shipping_rate', 10, 2 );