简体   繁体   English

Wordpress 'wp_enqueue_script' 不能在 'wp_login' 钩子上工作

[英]Wordpress 'wp_enqueue_script' not working on 'wp_login' hook

I want to execute a javascript when user logs in into my wordpress system.当用户登录到我的 wordpress 系统时,我想执行 javascript。 To be specific I need to execute a Google Tag Manager Javascript.具体来说,我需要执行一个谷歌标签管理器 Javascript。 Please refer the code below,请参考下面的代码,

function gtm_wp_login() {
    wp_enqueue_script( 'gtm-on-login', get_stylesheet_directory_uri() . '/assets/js/gtm_on_login.js', array());
    echo "<script>alert('Welcome');</script>";
    echo "One";
    echo "<script>console.log('Welcome Theme');</script>";
    echo "Two";
    print_r($_REQUEST);
    echo "Three";
    die();
}
add_action( 'wp_login', 'gtm_wp_login');

I put the above code in the functions.php file of Wordpress theme.我把上面的代码放在Wordpress主题的functions.php文件中。 In enqueued file gtm_on_login.js, I have only done console.log at the moment to check if it gets enqueued.在入队文件 gtm_on_login.js 中,我目前只完成了 console.log 来检查它是否入队。 I got to see a weird behavior, when I put die() statement at the end of callback function当我将 die() 语句放在回调 function 的末尾时,我看到了一个奇怪的行为

  1. the inline javascript echoed, shows the output including the alert('Welcome') statement.内联 javascript 回显,显示output 包括 alert('Welcome') 语句。
  2. the console.log in enqueued script do not display.排队脚本中的 console.log显示。 (I checked the wp_enqueue_script statement by putting it outside the callback to check its syntax correctness, it shows output in that case) (我通过将 wp_enqueue_script 语句放在回调之外检查它的语法正确性来检查它,在这种情况下它显示 output)

However, on removing the die() statement neither Pt 1 nor Pt.但是,在删除 die() 语句时,既不是 Pt 1 也不是 Pt。 2 output gets displayed, In other words, no javascript gets entertained in the flow. 2 output 得到显示,换句话说,没有 javascript 在流程中得到娱乐。 Please guide, how can I execute a script by enqueing and echoing it directly when user logs in the wordpress system.请指导,当用户登录 wordpress 系统时,如何通过直接入队和回显来执行脚本。

I think you're approaching this problem slightly incorrectly.我认为你处理这个问题有点不正确。 Have you verified 100% that your script is inside the source code of the login page?您是否 100% 验证了您的脚本在登录页面的源代码中? I'm willing to bet that you won't find your added JS on that login page.我敢打赌你不会在那个登录页面上找到你添加的 JS。

What you are trying to utilize wp_enqueue_script which doesn't work properly with adding the said scripts to particular pages that are deemed as backend WordPress pages.您尝试使用的wp_enqueue_script在将上述脚本添加到被视为后端 WordPress 页面的特定页面时无法正常工作。 This is an action hook which injects scripts/styles even if need be to the front-end of the site.这是一个动作钩子,即使需要注入站点的前端,它也会注入脚本/样式。

From what I'm gathering, you're trying to track users in the WP backend after they've logged in, or have some sort of a trigger hit when they do log into the WP backend.从我收集的信息来看,您正在尝试在 WP 后端登录后跟踪用户,或者在他们登录 WP 后端时触发某种触发器。 In order to do this properly and have it work with a WP login page I would look into creating a front-end login utility which is more or less just an empty page with your header, and footer.为了正确执行此操作并使其与 WP 登录页面一起使用,我将考虑创建一个前端登录实用程序,该实用程序或多或少只是一个带有 header 和页脚的空白页面。 This will allow you to control exactly what is injected and ran on that particular page without really trying to mess around with injecting scripts into the admin-core.这将允许您准确控制在该特定页面上注入和运行的内容,而无需真正尝试将脚本注入管理核心。 Furthermore, you can then lean on GTM to create a trigger when that particular button is either clicked, or there is some sort of a successful message posted to the user, which would then track the data independently in your GTM dashboard.此外,您可以依靠 GTM 在单击该特定按钮或向用户发布某种成功消息时创建触发器,然后在您的 GTM 仪表板中独立跟踪数据。

Here's some supporting code which can get you started on the custom login page.下面是一些支持代码,可以帮助您开始自定义登录页面。 Keep in mind you might want to create a custom page template and delegate this code towards that rather than the wp-login.php page like the code in this example:请记住,您可能希望创建一个自定义页面模板并将此代码委托给该模板,而不是 wp-login.php 页面,如本示例中的代码:

/* Main redirection of the default login page */
function redirect_login_page() {
    $login_page  = home_url('/login/');
    $page_viewed = basename($_SERVER['REQUEST_URI']);

    if($page_viewed == "wp-login.php" && $_SERVER['REQUEST_METHOD'] == 'GET') {
        wp_redirect($login_page);
        exit;
    }
}
add_action('init','redirect_login_page');

/* Where to go if a login failed */
function custom_login_failed() {
    $login_page  = home_url('/login/');
    wp_redirect($login_page . '?login=failed');
    exit;
}
add_action('wp_login_failed', 'custom_login_failed');

/* Where to go if any of the fields were empty */
function verify_user_pass($user, $username, $password) {
    $login_page  = home_url('/login/');
    if($username == "" || $password == "") {
        wp_redirect($login_page . "?login=empty");
        exit;
    }
}
add_filter('authenticate', 'verify_user_pass', 1, 3);

/* What to do on logout */
function logout_redirect() {
    $login_page  = home_url('/login/');
    wp_redirect($login_page . "?login=false");
    exit;
}
add_action('wp_logout','logout_redirect');

Some useful information for reference: https://themetrust.com/build-custom-wordpress-login-page/一些有用的信息供参考: https://themetrust.com/build-custom-wordpress-login-page/

The solution that worked for me, may be it is a work around.对我有用的解决方案可能是一种变通方法。

In the functions.php of my theme folder I added the following code,在我的主题文件夹的functions.php中,我添加了以下代码,

add_filter('login_redirect', 'login_query_parameter', 99, 3);

function login_query_parameter($url, $request, $user) {
    if(strpos($url, 'wp-admin') !== false) {
        return $url;
    }
    else {
        return $url."?login=success";
    }   
}

I have added if else in above code, as I only want to track login via frontend and not wordpress backend.我在上面的代码中添加了 if else,因为我只想通过前端而不是 wordpress 后端跟踪登录。 Further in functions.php file of the theme I am enqueing the script if the user is found logged in.进一步在functions.php主题文件中,如果发现用户登录,我将加入脚本。

if(is_user_logged_in()) {
        wp_enqueue_script( 'gtm-on-login', get_stylesheet_directory_uri() . '/assets/js/gtm_on_login.js', array());
        wp_localize_script(
            'gtm-on-login',
            'gtm_on_login_obj',
            array(
                'user_id' => get_current_user_id()              
            )
        );

    }

I am enqueuing the script if the user is found logged in and passing the necessary data using wp_localize_script() function, in my case current user's id.如果发现用户已登录并使用 wp_localize_script() function(在我的情况下为当前用户的 ID)传递必要的数据,我会将脚本排入队列。

And inside the gtm_on_login.js,在 gtm_on_login.js 里面,

var url = window.location.toString();
if(url.indexOf("login=success") > -1) {
   
  // Any Javacript to execute on Login, in my case GTM Code

   var trimmed_uri = url.replace('?login=success','');
   window.history.replaceState({}, document.title, trimmed_uri); 
} 

So now with the above set of code, gtm_on_login.js is loaded on the page only when user is found logged in and the based on the query parameter check my javascript gets executed only once when user logs in. The following 2 lines in above code removes the query parameter from the url to prevent re-execution of the script on same page reload.所以现在使用上面的代码集,gtm_on_login.js 仅在用户登录时加载到页面上,并且基于查询参数检查我的 javascript 仅在用户登录时执行一次。上面代码中的以下 2 行从 url 中删除查询参数,以防止在同一页面重新加载时重新执行脚本。

var trimmed_uri = url.replace('?login=success','');
window.history.replaceState({}, document.title, trimmed_uri);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM