我对WP和JS都很陌生,需要对现有代码做一个简单的更改,所以请原谅我的无知…
为了获取当前的用户Id,我遵循示例并在函数中添加了一个action+函数。我的孩子主题的php(粘贴在下面)现在我需要在<script>…. </script>
我试图将其分配到一个var中,但失败了(下面还粘贴了一个示例脚本部分,其中包含不起作用的分配)。
How do I do that right?
Added to functions.php:
add_action(\'init\',’my demo_function\');
function my demo_function(){
$theid=get_current_user_id();
$params = array(
\'userid\' => $theid
);
wp_localize_script( \'myuserscript\', \'MyUserParams\', $params );
wp_enqueue_script(\'myuserscript\');
}
我在WP页面中尝试的代码示例(失败)
<script>
// when using this line I get the alert, as expected
// var myData = "1234";
// but when using this, alert is skipped, I suppose because this assignment is invalid
var myData = MyUserParams.userid;
alert("your id is: " + myData)
</script>
最合适的回答,由SO网友:Tunji 整理而成
您必须确保您的脚本已注册到wp_register_script
在您致电之前wp_localize_script
.
所以在你的函数中。php文件:
add_action(\'init\',’my demo_function\');
function my demo_function() {
// Register the script
wp_register_script( \'myuserscript\', \'path/to/myscript.js\' );
// Localize the script with your data
$theid=get_current_user_id();
$params = array(
\'userid\' => $theid
);
wp_localize_script( \'myuserscript\', \'MyUserParams\', $params );
// Enqueued script with localized data.
wp_enqueue_script(\'myuserscript\');
}
然后,您可以在前端使用该参数
<script>
var myData = MyUserParams.userid;
alert("your id is: " + myData)
</script>
Reference: wp_localize_script