(更新/新答案)
如何让它在前端以短代码显示“美国(US)”?
首先,你有united-states
(国家/地区段塞/键)而不是United States (US)
(国家名称)因为extrainfo_save_extra_user_profile_fields()
功能是保存国家/地区段塞/键,而不是国家/地区名称。这不是问题,我也会这么做。
However, to display the proper country name based on its slug/key, 然后:
一种简单的方法是复制国家代码/键和名称array
从您的extrainfo_show_extra_profile_fields()
函数到您的快捷码函数;e、 g.:
function user_country_info_shortcode() {
if(is_user_logged_in()) {
$user_id = get_current_user_id();
$country = get_user_meta($user_id, \'country\', true);
if (!empty($country)) {
$countrys = array(
\'not-selected\' => \'\',
\'south-africa\' => \'South Africa\',
\'south-korea\' => \'South Korea\',
\'spain\' => \'Spain\',
\'ukraine\' => \'United Arab Emirates\',
\'united-kingdom\' => \'United Kingdom (UK)\',
\'united-states\' => \'United States (US)\',
\'venezuela\' => \'Venezuela\',
\'vietnam\' => \'Vietnam\',
);
$country = isset( $countrys[ $country ] ) ? $countrys[ $country ] : $country;
echo $country;
} else {
echo \'Add your country\';
}
}
}
但要获得更大的灵活性;无需编辑两个函数代码,只需更改特定的国家/地区代码/键和/或名称,然后我强烈建议您使用下面的其他选项,尤其是当您有一个(非常)长的国家/地区列表时:
在主题函数文件中(例如。wp-content/themes/your-child-theme/functions.php
), 或在存储全局函数的插件文件中,添加以下内容:
// List of country slugs and names.
function my_user_country_list() {
return array(
\'not-selected\' => \'\',
\'south-africa\' => \'South Africa\',
\'south-korea\' => \'South Korea\',
\'spain\' => \'Spain\',
\'ukraine\' => \'United Arab Emirates\',
\'united-kingdom\' => \'United Kingdom (UK)\',
\'united-states\' => \'United States (US)\',
\'venezuela\' => \'Venezuela\',
\'vietnam\' => \'Vietnam\',
);
}
然后在
extrainfo_show_extra_profile_fields()
功能,更换
foreach
(打开线),以便使用
my_user_country_list()
函数,如下所示:
function extrainfo_show_extra_profile_fields( $user ) { ?>
<h3 class="extra-info">Extra Info</h3>
<table class="form-table">
<tr>
<th><label for="country">Country</label></th>
<td>
<select name="country" id="country" >
<?php
$_value = trim( get_user_meta( $user->ID, \'country\', true ) );
foreach ( my_user_country_list() as $value => $label ) :
$selected = selected( $value, $_value, false );
?>
<option value="<?php echo esc_attr( $value ); ?>"<?php echo $selected; ?>><?php echo esc_html( $label ); ?></option>
<?php endforeach; ?>
</select>
</td>
</tr>
</table>
<?php }
然后,在你的
user_country_info_shortcode()
功能,您可以检索用户的国家(即国家名称),如下所示:
(为了清晰起见,缩进)function user_country_info_shortcode() {
if(is_user_logged_in()) {
$user_id = get_current_user_id();
$country = get_user_meta($user_id, \'country\', true);
if (!empty($country)) {
$countrys = my_user_country_list();
$country = isset( $countrys[ $country ] ) ? $countrys[ $country ] : $country;
echo $country;
} else {
echo \'Add your country\';
}
}
}
很抱歉这么多的编辑,但希望这个“新”答案比原来的答案(或之前对这个答案的修订)更有帮助