简体   繁体   中英

Adding Custom Cookie To Wordpress

Hi I am pretty new to wordpress,php and all this editing thing. I want to add a new cookie to wordpress upon authentication with name "xxx" and value "(currentusername)". I already read 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. Thanks in advance

Here is the code on the other website which I inserted in my 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');

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. 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 :

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. Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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