如果要在任何地方使用该函数,需要确保:
我还对您的代码进行了一些更改,简化和压缩了代码。
现在,您可以在所有可用的动作挂钩中使用此函数。
您还可以在任何模板或php文件中使用它,只需一行:
location_select_account();
您重新访问的代码:
add_action( \'woocommerce_account_content\' , \'location_select_account\' , 5 );
function location_select_account() {
global $current_user;
if( ! is_a( $current_user, \'WP_User\' ) )
$current_user = wp_get_current_user();
if( $current_user->ID === 0 ) {
return; // Exit
}
// Get the posted data and update user meta data
if( isset($_POST[\'location_select\']) ) {
$locationposter = $_POST[\'location_select\'];
// Update/Create User Meta
update_user_meta( $current_user->ID, \'location_select\', $locationposter );
}
?>
<form method="POST">
<?php
//get dropdown saved value
$selectedinfo = $current_user->location_select;
?>
<select name="location_select" id="location_select" style="width:13em;" onchange="this.form.submit()">
<option value="all_of_canada" <?php echo ($selectedinfo == "all_of_canada")? \'selected="all_of_canada"\' : \'\' ?>>All of Canada</option>
<option value="abbotsford" <?php echo ($selectedinfo == "abbotsford")? \'selected="abbotsford"\' : \'\' ?>>Abbotsford</option>
<option value="barrie" <?php echo ($selectedinfo == "barrie")? \'selected="barrie"\' : \'\' ?>>Barrie</option>
<option value="brantford" <?php echo ($selectedinfo == "brantford")? \'selected="brantford"\' : \'\' ?>>Brantford</option>
</select>
</form>
<script>
jQuery( function($){
// Check if select2 jQuery plugin is loaded
if (typeof $().select2 !== \'undefined\') {
$(\'#location_select\').select2();
};
});
</script>
<?php
}
代码进入函数。活动子主题(或活动主题)的php文件或插件文件。已测试并正常工作。
<小时>
Bonus - Using the function as a shortcode
add_shortcode( \'location_select\', \'location_select_shortcode\' );
function location_select_shortcode(){
ob_start(); // Start buffering
location_select_account();
return ob_get_clean();
}
代码进入函数。活动子主题(或活动主题)的php文件或插件文件。已测试并正常工作。
USAGE:
1) 在Wordpress编辑器中:
[location_select]
2在php文件中:
echo do_shortcode( "[location_select]" );