最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp localize script - How can I get user data into a javascript object?

programmeradmin1浏览0评论

I have the code below in my functions.php file. However, when I try to access the variable theUser in my custom.js file it comes back as undefined.

Functions.php:

function theme_scripts() {
     global $current_user;
     $current_user = wp_get_current_user();

     wp_enqueue_script( 'theme-script', get_stylesheet_directory_uri() . '/assets/js/custom.js', array( 'jquery' ), '', true );
     wp_localize_script( 'theme-script', 'theUser', array (
        'username' => $current_user,
     ) );
  }
  add_action( 'wp_enqueue_scripts', 'theme_scripts' );

Custom.js:

var theUser;
var userName = theUser.username.data.display_name;
var userEmail = theUser.username.data.user_email;
console.log(theUser);

I have the code below in my functions.php file. However, when I try to access the variable theUser in my custom.js file it comes back as undefined.

Functions.php:

function theme_scripts() {
     global $current_user;
     $current_user = wp_get_current_user();

     wp_enqueue_script( 'theme-script', get_stylesheet_directory_uri() . '/assets/js/custom.js', array( 'jquery' ), '', true );
     wp_localize_script( 'theme-script', 'theUser', array (
        'username' => $current_user,
     ) );
  }
  add_action( 'wp_enqueue_scripts', 'theme_scripts' );

Custom.js:

var theUser;
var userName = theUser.username.data.display_name;
var userEmail = theUser.username.data.user_email;
console.log(theUser);
Share Improve this question asked Jun 22, 2020 at 19:14 Lz430Lz430 1378 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

that's because you have defined the variable theUser as null and overridden the one that has the object before then you have tried to call the object.

just remove this line var theUser;

发布评论

评论列表(0)

  1. 暂无评论