将自定义Cookie添加到Wordpress

时间:2013-06-11 19:51:06

标签: php wordpress cookies

嗨我对wordpress,php和所有这些编辑工具都很新。我想在认证时向wordpress添加一个新的cookie,名称为“xxx”,值为“(currentusername)”。我已经阅读了http://wptheming.com/2011/04/set-a-cookie-in-wordpress/。我将所需的代码添加到我的代码的functions.php中,但是我不知道如何调用它,以便将当前用户名logginned添加到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');

1 个答案:

答案 0 :(得分:1)

归结为这个 - 我建议不要添加新的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用于此代码。祝你好运。