Maryam
Maryam

Reputation: 146

Change the way the address is displayed via my-account/my-address.php template file in WooCommerce

I would like to modify the output of $address, which can be found at line 67 (@version 2.6.0) in the /myaccount/my-address.php template file.

The template file itself has following code:

<address>
    <?php
        echo $address ? wp_kses_post( $address ) : esc_html_e( 'You have not set up this type of address yet.', 'woocommerce' );
    ?>
</address>

The output of this code is for example:

Marke
1 Frazer Lane, New Oxford,pa, 13350 United States

But I am trying to add a title to each line for example:

Name: Marke
Address: 1 Frazer Lane, New Oxford,pa, 13350 United States

So I applied the following adjustment in the template file:

<address>
<?php
if ( $address) {
    // Split a string by a string
    $myAddr= explode( '<br/>', $address);
    
    // Loop
    foreach ( $pieces as $piece ) {
        echo '<p>' . 'Title: ' . $myAddr. '</p>';
    }
} else {
    echo esc_html_e( 'You have not set up this type of address yet.', 'woocommerce' );
}
?>
</address>

Right here I can just add the <br> tag to make the information clear but I can't add a different title to each line. Any advice?

Upvotes: 1

Views: 573

Answers (1)

7uc1f3r
7uc1f3r

Reputation: 29614

You can indeed overwrite the template file. Another option, however, is to use the woocommerce_my_account_my_address_formatted_address filter hook.

Based on the key you can add a prefix, as well as remove fields (via unset()) or merge. In short: it depends on your specific wishes.

So you get:

function filter_woocommerce_my_account_my_address_formatted_address( $address, $customer_id, $address_type ) {
    // Loop
    foreach ( $address as $key => $part ) {
        // First name
        if ( $key == 'first_name' ) {
            // Add prefix
            $address[$key] = __( 'Name: ', 'woocommerce' ) . $part;
        // Address 1
        } elseif ( $key == 'address_1' ) {
            // Add prefix
            $address[$key] = __( 'Address: ', 'woocommerce' ) . $part;
        }
    }    

    return $address;
}
add_filter( 'woocommerce_my_account_my_address_formatted_address', 'filter_woocommerce_my_account_my_address_formatted_address', 10, 3 );

Code goes in functions.php file of the active child theme (or active theme).


Result:

enter image description here

Upvotes: 1

Related Questions