add_shortcode( 'user_state', function( $atts = array(), $content = '' ) {
if ( is_user_logged_in() ) {
$atts = shortcode_atts(
array(
'field' => '',
'width' => '100',
),
$atts
);
$user_id = get_current_user_id();
// Get the 2 character state value like 'al', 'fl', 'tx', etc.
$user_state = get_field( 'user_state', 'user_' . $user_id );
$user_state_label = '';
if ( 'false' !== $user_state ) {
/**
* Validate the $user_state value by checking the choices for the field. This is
* done in case the overall choices changes and we have to revert the user value
* to some default value.
*/
$user_state_field = get_field_object( 'user_state', 'user_' . $user_id );
if ( ! isset( $user_state_field['choices'][ $user_state ] ) ) {
$user_state = 'false';
} else {
$user_state_label = $user_state_field['choices'][ $user_state ];
}
}
/**
* Now work on the returned values.
*/
switch ( $atts['field'] ) {
case 'image':
/**
* Assumed we have a directory off the site root containing all the US state images where the
* the image filenames are all in a pattern using the 2 character state code like:
* al - Alabama - https://www.site.com/images-state-logos/al.png
* fl - Florida - https://www.site.com/images-state-logos/fl.png
* tx - Texas - https://www.site.com/images-state-logos/tx.png
*
* But these image coould be external or anywhere else within the site.
*/
if ( ( 'false' !== $user_state ) && ( file_exists( ABSPATH . '/images-state-logos/' . $user_state . '.png' ) ) ) {
// If the $user_state is not false and the state image exists then show it.
$content .= '<img width="' . $atts['width'] . '" src="/images-state-logos/' . $user_state . '.png" alt="' . $user_state_label . '" />';
} else {
// If the user state is false or the state image does not exist we show a default logo.
$content .= '<img width="' . $atts['width'] . '" src="/images-state-logos/default.png" alt="' . $user_state_label . '" />';
}
break;
case 'label':
// We want to return the state full name.
$content .= $user_state_label;
break;
case '':
default:
// By default we want to return the state aabbreviation.
if ( 'false' !== $user_state ) {
$content .= $user_state;
}
break;
}
}
return $content;
}, 30, 2 );
Copy to clipboard