WooCommerce: Get formatted store address

When developing extension for WooCommerce, Sometimes you’ll need to display the formatted store address. Admin can set their store address from WooCommerce Settings.

But, I didn’t find the method where i can retrieve the formatted store address with city, state, country like Order object has. So, I’ve to create my own method to done this.

You can easily get address line 1, address line 2, city, state, country values from some helpful methods in WC_Countries class.

WC()->countries->get_base_address(); // address line 1
WC()->countries->get_base_address_2(); // address line 2
WC()->countries->get_base_city(); // city
WC()->countries->get_base_state(); // state
WC()->countries->get_base_postcode(); // postcode/zip
WC()->countries->get_base_country();// country
PHP

Let’s define a method which return formatted store address

/**
  * Return formatted store address.
	*
	* @return array
*/
function get_formatted_store_address() {
		return WC()->countries->get_formatted_address(
			array(
				'address_1' => WC()->countries->get_base_address(),
				'address_2' => WC()->countries->get_base_address_2(),
				'city'      => WC()->countries->get_base_city(),
				'state'     => WC()->countries->get_base_state(),
				'postcode'  => WC()->countries->get_base_postcode(),
				'country'   => WC()->countries->get_base_country(),
			)
		);
}
PHP

Here, I use get_formatted_address method which defined in WC_Countries class. Because, other plugins can modify WooCommerce’s default structure of address format.

Thanks.

Istiaq Nirab

A highly skilled and proficient WordPress developer with over Three years of professional experience in all aspects of WordPress website creation, including design, plug-ins, and implementation. Results-driven individual contributor with a successful track record in exceeding expectations for web development initiatives

More Reading

Post navigation

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *