简体   繁体   English

将自定义Cookie添加到Wordpress

[英]Adding Custom Cookie To Wordpress

Hi I am pretty new to wordpress,php and all this editing thing. 嗨,我对wordpress,php和所有这些编辑工作还很陌生。 I want to add a new cookie to wordpress upon authentication with name "xxx" and value "(currentusername)". 我想在身份验证时使用名称“ xxx”和值“(currentusername)”向wordpress添加新的cookie。 I already read http://wptheming.com/2011/04/set-a-cookie-in-wordpress/ . 我已经阅读了http://wptheming.com/2011/04/set-a-cookie-in-wordpress/ I add the required code to the functions.php of my code however I don't know how to invoke it such that the currentusername logginned is added to the cookie. 我将所需的代码添加到我的代码的functions.php中,但是我不知道如何调用它,以便将logginned的currentusername添加到cookie中。 Thanks in advance 提前致谢

Here is the code on the other website which I inserted in my functions.php 这是我插入在functions.php中的另一个网站上的代码

function set_newuser_cookie() {
if (!isset($_COOKIE['sitename_newvisitor'])) {
    setcookie('sitename_newvisitor', 1, time()+1209600, COOKIEPATH, COOKIE_DOMAIN, false);
}

} add_action( 'init', 'set_newuser_cookie'); } add_action('init','set_newuser_cookie');

Bumped into this one - I recommend against adding a new cookie, instead I would hijack (take advantage of) the current cookie and let WP manage it for you. 碰到这个-我建议不要添加新的cookie,相反,我会劫持(利用)当前的cookie,并让WP为您管理它。 Additionally the hooks available in WP allow very clean and tight code using WP features - try the snippet below - I put in comments and tried to be verbose : 另外,WP中的可用钩子允许使用WP功能实现非常干净和紧密的代码-尝试以下代码段-我在注释中添加了详细信息:

function custom_set_newuser_cookie() {
    // re: http://codex.wordpress.org/Function_Reference/get_currentuserinfo
    if(!isset($_COOKIE)){ // cookie should be set, make sure
        return false; 
    }
    global $current_user; // gain scope
    get_currentuserinfo(); // get info on the user
    if (!$current_user->user_login){ // validate
        return false;
    }
    setcookie('sitename_newvisitor', $current_user->user_login, time()+1209600, COOKIEPATH, COOKIE_DOMAIN, false); // change as needed
}
// http://codex.wordpress.org/Plugin_API/Action_Reference/wp_login
add_action('wp_login', 'custom_set_newuser_cookie'); // will trigger on login w/creation of auth cookie
/**
To print this out
if (isset($_COOKIE['sitename_newvisitor'])) echo 'Hello '.$_COOKIE['sitename_newvisitor'].', how are you?';
*/

And yes, use functions.php for this code. 是的,为此代码使用functions.php。 Good luck. 祝好运。

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

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