用户注册后在WordPress页眉上打印脚本

时间:2015-09-02 作者:user44321

在我的wordpress站点上注册用户后,我应该附加javascript snipet,我像这样使用user\\u register挂钩

do_action(\'user_register\', $user_id );
add_action(\'user_register\', \'MY_Callback\');
function MY_Callback(){
  $data[\'user_id\'] = $user_id;
  My_print_js($data);
}
然后在my\\u print\\u js函数中

function My_print_js(){
   global $data;
   echo \'<script>\';
   echo \'dlayer.push(\'.json_encode($data).\')\'
   echo \'</script>\';
}
在user\\u注册后脚本没有打印,我错过了什么?我注意到我也使用woocommerce。

感谢大家的帮助:)

1 个回复
SO网友:TheDeadMedic

这里有很多问题:

do_action(\'user_register\', $user_id );
无需自己启动操作(尤其是使用未定义的变量$user_id) - 行动的理念;过滤器是将函数“挂钩”到一个,然后让WordPress在适用时触发它。

function MY_Callback(){
  $data[\'user_id\'] = $user_id;
  My_print_js($data);
}
又一次$user_id 未定义(null)-您需要在函数中接受它作为参数:

function MY_Callback( $user_id ) {
第二个函数也存在同样的问题-使用参数调用它(如上所述),但完全忽略它并尝试使用全局$data - 相反,您希望:

function My_print_js( $data /* Take the argument man! */ ) {
   echo \'<script>\';
   echo \'dlayer.push(\'.json_encode($data).\')\'
   echo \'</script>\';
} 
现在来看最后一个问题:即使您应用了以上所有内容,您的代码也不太可能工作,因为无法确定user_register 操作将启动-您的代码只需打印<script> 标记,但不能保证它在HTML文档的上下文中,或者它甚至可以打印(如果后面紧接着有重定向头怎么办?)。

我建议使用以下方法,然后测试它是否适用于以下场景:user_register 在需要的地方开火:

function wpse_200441_user_register( $user_id ) {
    global $wpse_200441_user_register;

    // Store the user ID that just registered in a global so that the script
    // function can access it later.
    $wpse_200441_user_register = $user_id;

    // Hook the script function
    add_action( \'wp_footer\', \'wpse_200441_script\' );
}

add_action( \'user_register\', \'wpse_200441_user_register\' );

function wpse_200441_script() {
    global $wpse_200441_user_register;

    if ( ! empty( $wpse_200441_user_register ) ) {
        $json = json_encode(
            array(
                \'user_id\' => $wpse_200441_user_register,
            )
        );

        echo "<script>dlayer.push( $json );</script>"; 
    }
}