繁体   English   中英

将自定义Cookie添加到Wordpress

[英]Adding Custom Cookie To Wordpress

嗨,我对wordpress,php和所有这些编辑工作还很陌生。 我想在身份验证时使用名称“ xxx”和值“(currentusername)”向wordpress添加新的cookie。 我已经阅读了http://wptheming.com/2011/04/set-a-cookie-in-wordpress/ 我将所需的代码添加到我的代码的functions.php中,但是我不知道如何调用它,以便将logginned的currentusername添加到cookie中。 提前致谢

这是我插入在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');

碰到这个-我建议不要添加新的cookie,相反,我会劫持(利用)当前的cookie,并让WP为您管理它。 另外,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?';
*/

是的,为此代码使用functions.php。 祝好运。

暂无
暂无

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

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