Cookies in WordPress

WordPress uses cookies, the small pieces of information stored on your computer, to verify who you are. There are cookies for logged in users and for commenters. On login, wordpress uses the wordpress_[hash] cookie to store your authentication details.

How to Set Cookies

After login, wordpress sets the wordpress_logged_in_[hash] cookie, which indicates when you’re logged in. WordPress also sets a few wp-settings-{time}-[UID] cookies. The number on the end is your individual user ID from the users database table.

The functions to set and remove cookies are defined in /wp-includes/pluggable.php.

  • wp_set_auth_cookie( $user_id, $remember, $secure )  – This function sets the cookie.
  • wp_clear_auth_cookie()  – This function will delete the cookie from the client browser.
  • auth_redirect()  – This function also utilizes the cookies. Checks whether the cookie is present on the client browser. If it is not, the user is sent to the wp-login.php login screen.

 

When visitors comment on your blog, they too get cookies stored on their computer. There are three cookies are set for commenters:

  • comment_author_{HASH}
  • comment_author_email_{HASH}
  • comment_author_url_{HASH}

 

 

More option to Setting Cookies

<?php
    add_action( 'init', 'my_setcookie_example' );
    function my_setcookie_example() {
   setcookie( $visitor_username, $username_value, 3 * DAYS_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
    }
?>

Getting Cookies

<?php
    if(!isset($_COOKIE[$visitor_username])) {
    echo "The cookie: '" . $visitor_username . "' is not set.";
    } else {
    echo "The cookie '" . $visitor_username . "' is set.";
    echo "Value of cookie: " . $_COOKIE[$visitor_username];
    }
?>

Deleting Cookies

<?php
unset( $_COOKIE[$visitor_username] );
setcookie( $visitor_username, '', time() - ( 15 * 60 ) );
?>

Leave a Reply

Your email address will not be published.

*