您需要使用wp_localize_script() 函数,该函数允许您创建JavaScript对象,使用PHP填充数据,然后将其传递到JavaScript文件中。
这是在您的functions.php 将JavaScript文件排队的函数中的文件。您需要向它传递您将脚本作为队列的句柄、要在JavaScript中使用的对象的名称以及对象的属性和值数组。
从那时起,您只需使用wp_get_current_user() 函数获取您的值。
例如:
function theme_scripts() {
global $current_user;
$current_user = wp_get_current_user();
wp_enqueue_script( \'theme-script\', get_template_directory_uri() . \'/js/functions.js\', array( \'jquery\' ), \'\', true );
wp_localize_script( \'theme-script\', \'theUser\', array (
\'username\' => $current_user->user_login,
) );
}
add_action( \'wp_enqueue_scripts\', \'theme_scripts\' );
问题是
$current_user 默认情况下,不会在您的enqueue函数中填充,因此您需要在前面的某个地方调用它,如下所示:
global $current_user;
$current_user = wp_get_current_user();
现在可以在脚本中访问此对象,并为数组中放置的每个键提供属性。因此,在这种情况下,您可以访问用户的登录名
theUser.username.