简体   繁体   English

登录后在第一页加载时向wordpress网站添加代码

[英]Adding code to wordpress site on first page load after login

I'm writing a wordpress plugin where I need to inject a beacon (HTML image tag) into the page on the first page load after the user logs in - ie the page they are redirected to. 我正在写一个wordpress插件,我需要在用户登录后在第一页加载的页面中注入一个信标(HTML图像标记) - 即他们被重定向到的页面。 Subsequent page views of the same or other pages should not include this beacon code. 相同页面或其他页面的后续页面视图不应包含此信标代码。

I've tried several ways to do this. 我已经尝试了几种方法来做到这一点。

I've added a function to the wp_login hook. 我已经在wp_login钩子中添加了一个函数。 From this function I've tried adding another function to the wp_footer hook to output the content. 从这个函数我已经尝试添加另一个函数到wp_footer钩子来输出内容。

// in my class constructor
add_action('wp_login', array($this, 'login'));

public function login() {
    add_action('wp_footer', array($this, 'add_beacon'));
}

This didn't work so I tried setting both hooks up front and setting a global variable to indicate first load. 这没有用,所以我尝试在前面设置两个钩子并设置一个全局变量来指示第一次加载。 That wasn't picked up by my second function and neither was a constant. 我的第二个功能没有提到这一点,也不是一个常数。

// in my class constructor
add_action('wp_login', array($this, 'login'));
add_action('wp_footer', array($this, 'add_beacon'));

public function login() {
    define('FIRST_RUN', true);
}

public function add_beacon() {
    if (defined('FIRST_RUN')) {
        // output beacon
    }
}

Both hook functions fire correctly but whenever I try to make the output of content in the second dependent on the first hook function firing I get no output. 两个钩子函数都正确触发但是每当我尝试使第二个内容的输出依赖于第一个钩子函数触发时我都没有输出。

Any ideas how I can do this? 我有什么想法可以做到这一点? Perhaps there's some way I can check without using the wp_login hook at all. 也许我可以在不使用wp_login挂钩的情况下检查某些方法。

Try using a per session cookie. 尝试使用每个会话cookie。

The code would be something like: 代码如下:

function my_init() { 
  if ( is_user_logged_in() ) {  
    if (!isset($_COOKIE['beacon'])) {  
      //Track user code / add wp_footer action
      setcookie ('beacon' 'tracked'); 
    }
  }
}
add_action('init','my_init');

(Code not tested.. hopefully you get the idea). (代码没有经过测试..希望你能得到这个想法)。

If you're not happy with the cookie, you could store last page loaded by user in the usermeta table... however, you'd have to make a call as to how long since last page load is considered a new session. 如果您对cookie不满意,可以将用户加载的最后一页存储在usermeta表中...但是,您必须调用上次页面加载被视为新会话的时间。

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

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