如何在WP页面的脚本中获取WP入队脚本(在Functions.php中)?

时间:2016-12-29 作者:Yoav Ossia

我对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>

1 个回复
最合适的回答,由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

相关推荐

Why won't my scripts load?

在函数中加载脚本时遇到问题。php我以前做过这件事,所以我肯定我忽略了一些东西,但就我所知,这是正确的,我尝试过从其他答案中复制和粘贴。我没有收到任何控制台错误。我的任何脚本都没有加载到源代码中。感谢您的帮助。functions.php/*SCRIPTS*/ add_action( \'wp_enqueue_scripts\', \'theme_js\' ); function theme_js(){ wp_register_script( \