0

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

4

1 回答 1

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。祝你好运。

于 2014-01-31T03:43:30.010 回答