WC_Countries::country_dropdown_options()publicWC 1.0

Outputs the list of countries and states for use in dropdown boxes.

Method of the class: WC_Countries{}

No Hooks.

Return

null. Nothing (null).

Usage

$WC_Countries = new WC_Countries();
$WC_Countries->country_dropdown_options( $selected_country, $selected_state, $escape );
$selected_country(string)
Selected country.
Default: ''
$selected_state(string)
Selected state.
Default: ''
$escape(true|false)
If we should escape HTML.
Default: false

WC_Countries::country_dropdown_options() code WC 9.4.2

public function country_dropdown_options( $selected_country = '', $selected_state = '', $escape = false ) {
	if ( $this->countries ) {
		foreach ( $this->countries as $key => $value ) {
			$states = $this->get_states( $key );
			if ( $states ) {
				// Maybe default the selected state as the first one.
				if ( $selected_country === $key && '*' === $selected_state ) {
					$selected_state = key( $states ) ?? '*';
				}

				echo '<optgroup label="' . esc_attr( $value ) . '">';
				foreach ( $states as $state_key => $state_value ) {
					echo '<option value="' . esc_attr( $key ) . ':' . esc_attr( $state_key ) . '"';

					if ( $selected_country === $key && $selected_state === $state_key ) {
						echo ' selected="selected"';
					}

					echo '>' . esc_html( $value ) . ' &mdash; ' . ( $escape ? esc_html( $state_value ) : $state_value ) . '</option>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

				}
				echo '</optgroup>';
			} else {
				echo '<option';
				if ( $selected_country === $key && '*' === $selected_state ) {
					echo ' selected="selected"';
				}
				echo ' value="' . esc_attr( $key ) . '">' . ( $escape ? esc_html( $value ) : $value ) . '</option>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			}
		}
	}
}