Php 向Wordpress添加自定义Cookie

Php 向Wordpress添加自定义Cookie,php,wordpress,cookies,Php,Wordpress,Cookies,嗨,我对wordpress、php和所有这些编辑工具都很陌生。我想在wordpress上添加一个名为“xxx”和值为“(currentusername)”的新cookie。我已经读过了。我将所需的代码添加到代码的functions.php中,但是我不知道如何调用它,从而将currentusername Loggined添加到cookie中。 提前谢谢 下面是我在functions.php中插入的另一个网站上的代码 function set_newuser_cookie() { if (!isse

嗨,我对wordpress、php和所有这些编辑工具都很陌生。我想在wordpress上添加一个名为“xxx”和值为“(currentusername)”的新cookie。我已经读过了。我将所需的代码添加到代码的functions.php中,但是我不知道如何调用它,从而将currentusername Loggined添加到cookie中。 提前谢谢

下面是我在functions.php中插入的另一个网站上的代码

function set_newuser_cookie() {
if (!isset($_COOKIE['sitename_newvisitor'])) {
    setcookie('sitename_newvisitor', 1, time()+1209600, COOKIEPATH, COOKIE_DOMAIN, false);
}
}
添加操作('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。祝你好运