如何在WordPress的jQuery(document).ready中显示已登录用户名
WordPress前端JS调用短代码获取当前登录用户解决方案
核心问题原因
WordPress短代码是服务端PHP环境下才能解析的内容,你写在前端JS文件里的[current_user]只是普通字符串,不会被PHP处理,所以无法正常输出用户信息。
方案1:JS代码写在PHP模板文件中(实现最简单)
如果你的这段jQuery代码是直接写在主题的页面模板(如page.php、footer.php、自定义页面模板等)里,直接用PHP解析短代码输出即可,修改后的代码如下:
jQuery( document ).ready(function($) { $('.uap-account-affiliatelinks-tab2 :lang(zh-hans)').append('<div id="affiliate_student_referal"><span>Student Instruction Link: https://f-tutor.com/zh-hans/?ref=<?php echo do_shortcode("[current_user]"); ?></span></div>'); });
注意:需要确保代码所在的模板文件是.php后缀,同时要判断用户登录状态的话可以加
<?php if (is_user_logged_in()) : ?>包裹JS代码,避免未登录时输出空值。
方案2:JS代码写在独立.js文件中(符合WordPress规范)
如果你的jQuery代码是存放在独立的JS文件中,需要通过WordPress官方推荐的wp_localize_script方法将服务端获取的用户信息传到前端JS全局变量中调用:
第一步:修改主题functions.php文件,添加传值逻辑
add_action('wp_enqueue_scripts', function() { // 此处替换为你的独立JS文件在WordPress中注册的句柄名 $js_handle = 'your-custom-js-handle'; $current_user_val = ''; if (is_user_logged_in()) { // 解析你定义的短代码获取用户值 $current_user_val = do_shortcode('[current_user]'); } // 注册全局变量到前端,变量名为wp_custom_data wp_localize_script($js_handle, 'wp_custom_data', [ 'current_user' => $current_user_val ]); });
第二步:修改你的jQuery代码,调用全局变量
jQuery( document ).ready(function($) { // 已登录有用户值时才插入内容 if (wp_custom_data.current_user) { $('.uap-account-affiliatelinks-tab2 :lang(zh-hans)').append('<div id="affiliate_student_referal"><span>Student Instruction Link: https://f-tutor.com/zh-hans/?ref=' + wp_custom_data.current_user + '</span></div>'); } });
内容的提问来源于stack exchange,提问作者Nicholas Lee
相关产品推荐
相关产品推荐

