Skip to content
Advertisement

How to get the complete state name from a WooCommerce order?

I’m new to WordPress and WooCommerce plugins and such. I’m writing a plugin and I need to send some data to a SOAP API, the case is that the API only accepts the state full name but I’m only getting the abbreviated form from WooCommerce.

require_once("grutinet-web-service.php");

add_action('woocommerce_thankyou', 'send_order_grutinet');
function send_order_grutinet($order_id)
{

// get order object and order details
$order = new WC_Order($order_id);

// set the address fields
$user_id = $order->get_user_id();
$address_fields = array(
    'country',
    'title',
    'first_name',
    'last_name',
    'company',
    'address_1',
    'address_2',
    'address_3',
    'address_4',
    'city',
    'state',
    'postcode'
);

$address = array();
if (is_array($address_fields)) {
    foreach ($address_fields as $field) {
        $address['billing_' . $field] = get_user_meta($user_id, 'billing_' . $field, true);
        $address['shipping_' . $field] = get_user_meta($user_id, 'shipping_' . $field, true);
    }
}


$numeroPedido   = $order_id;
$tipoPedido     = 'NORMAL';
$nombre         = $address['billing_first_name'] . $address['billing_last_name'];
$DniCif         = '41528741';
$direccion      = $address['shipping_address_1'] . ' - ' . $address['shipping_address_2'];
$codigoPostal   = $address['shipping_postcode'];
$poblacion      = $address['shipping_city'];
$provincia      = $order->get_shipping_state();
// $provincia      = $address['shipping_state'];
[...]

The important bit is:

$provincia      = $order->get_shipping_state();
// $provincia      = $address['shipping_state'];

How can I get the full state name here instead of the abbreviation?

Advertisement

Answer

You can use the following to display the state name from country and state codes:

$country_code = $order->get_shipping_country();
$state_code   = $order->get_shipping_state();

$countries = new WC_Countries(); // Get an instance of the WC_Countries Object

$country_states = $countries->get_states( $country_code ); // Get the states array from a country code
$state_name     = $country_states[$state_code]; // get the state name

// Display state name (for testing)
echo 'State name: ' . $state_name . '<br>';

Tested and works.

You can also use billing country and state with:

$country_code = $order->get_billing_country();
$state_code   = $order->get_billing_state();
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement