这将实现您想要的功能,这两个功能都应该放在fucntions.php 文件
这个my_random_string()
函数接受参数,因此您可以在字符串之前/之后添加数据,以及更改字符串的长度和用于生成字符串的字符。
/**
* Generate a string of random characters
*
* @param array $args The arguments to use for this function
* @return string|null The random string generated by this function (only \'if($args[\'echo\'] === false)\')
*/
function my_random_string($args = array()){
$defaults = array( // Set some defaults for the function to use
\'characters\' => \'0123456789\',
\'length\' => 10,
\'before\' => \'\',
\'after\' => \'\',
\'echo\' => false
);
$args = wp_parse_args($args, $defaults); // Parse the args passed by the user with the defualts to generate a final \'$args\' array
if(absint($args[\'length\']) < 1) // Ensure that the length is valid
return;
$characters_count = strlen($args[\'characters\']); // Check how many characters the random string is to be assembled from
for($i = 0; $i <= $args[\'length\']; $i++) : // Generate a random character for each of \'$args[\'length\']\'
$start = mt_rand(0, $characters_count);
$random_string.= substr($args[\'characters\'], $start, 1);
endfor;
$random_string = $args[\'before\'] . $random_string . $args[\'after\']; // Add the before and after strings to the random string
if($args[\'echo\']) : // Check if the random string shoule be output or returned
echo $random_string;
else :
return $random_string;
endif;
}
给你
my_on_user_register()
函数,每当生成新用户并将条目添加到
wp_usermeta
对照表
random_number
键,但显然可以根据需要更改此键的名称。
我还建议您看看Codex for the user_register
action.
/**
* Upon user registration, generate a random number and add this to the usermeta table
*
* @param required integer $user_id The ID of the newly registerd user
*/
add_action(\'user_register\', \'my_on_user_register\');
function my_on_user_register($user_id){
$args = array(
\'length\' => 6,
\'before\' => date("Y")
);
$random_number = my_random_string($args);
update_user_meta($user_id, \'random_number\', $random_number);
}
根据您的评论编辑回调函数
my_on_user_register()
现在将生成一个数字,该数字从当前年份开始,然后以随机的6个字符串(仅数字)结束。
您也可以使用下面的my_extra_user_profile_fields()
回调函数,用于在用户配置文件页面上输出随机数。但是请注意,此代码不允许用户编辑该数字。
/**
* Output additional data to the users profile page
*
* @param WP_User $user Object properties for the current user that is being displayed
*/
add_action(\'show_user_profile\', \'my_extra_user_profile_fields\');
add_action(\'edit_user_profile\', \'my_extra_user_profile_fields\');
function my_extra_user_profile_fields($user){
$random_number = get_the_author_meta(\'random_number\', $user->ID);
?>
<h3><?php _e(\'Custom Properties\'); ?></h3>
<table class="form-table">
<tr>
<th><label for="address"><?php _e(\'Random Number\'); ?></label></th>
<td><?php echo $random_number; ?></td>
</tr>
</table>
<?php
}