Display Customer Billing Address and Billing City Instead of "Shipping" Label on WooCommerce Checkout

Viewed 458

By using the woocommerce_shipping_package_name filter, I am looking to modify the label text to include, if the customer is logged in, the billing address and the billing city.

This is an example of the end result:

To be delivered to:

Main Street 1

New York

(without the extra rows in between)

I thought I had everything in place, but I'm getting an error.

Object of class WP_User could not be converted to int

I understand that a customer can register and then add a product to their cart and then go to checkout and if so -- there would be no billing address nor billing city. So, I really need to check if the meta is empty or not as well before proceeding to display the text (the expected output above).

Granted, I'm new at this and so.. asking for some help here.

My code so far:

add_filter( 'woocommerce_shipping_package_name', 'customer_address_city_with_shipping' );
function customer_address_city_with_shipping( $name ) {

    // only for logged in customers
    if (is_user_logged_in()){
    
    // get the current customer
    $user_id = wp_get_current_user();

    // make sure it's a valid customer ID
    if ($user_id == 0) return;

    // customer billing address and city, how to check if it's empty or not?
    $customer_address = get_user_meta( $user_id, 'shipping_address_1', true );
    $customer_city = get_user_meta( $user_id, 'shipping_city', true );

    // if logged in and if there's a billing address and billing city, let's go!
    return 'To be delivered to:<br /><span style="font-weight:normal!important;">'.$customer_address.'<br />'.$customer_city.'';

    } else {
    // if not.. then don't

    return 'Shipping &amp; Delivery';
    }
}
1 Answers

Thee are some mistakes in your code. try the following instead:

add_filter( 'woocommerce_shipping_package_name', 'customer_address_city_with_shipping' );
function customer_address_city_with_shipping( $name ) {
    // only for logged in customers
    if ( is_user_logged_in() && $user_id = get_current_user_id() ) {
        // Get customer shipping address and city
        $address = get_user_meta( $user_id, 'shipping_address_1', true );
        $city    = get_user_meta( $user_id, 'shipping_city', true );
        
        if( !empty($address) && !empty($city) ) {
            // Shipping address and city are not empty
            return __('To be delivered to:') . '<br /><span style="font-weight:normal !important;">' 
            . $address . '<br />' . $city . '</span>';
        } else {
            // Shipping address and city are not defined
            return 'Shipping &amp; Delivery';
        }
    } else {
        // User is not logged in
        return 'Shipping &amp; Delivery';
    }
}

Code goes in functions.php file of your active child theme (or active theme). It should works.

Related