aidaghazaryan aidaghazaryan - 1 year ago 88
PHP Question

track logged in user's cookie existence - wordpress

By default, wordpress creates cookie for logged in users which looks like this:

Cookie Name: wordpress_logged_in_a32e4aa16e20e5346cda1

I checked wordpress core file(wp-includes/default-constants.php) from where this cookie is being created. And how I saw the cookiehash after
is your site url done with md5().

if ( !defined( 'COOKIEHASH' ) ) {
$siteurl = get_site_option( 'siteurl' );
if ( $siteurl )
define( 'COOKIEHASH', md5( $siteurl ) );
define( 'COOKIEHASH', '' );
if ( !defined('LOGGED_IN_COOKIE') )
define('LOGGED_IN_COOKIE', 'wordpress_logged_in_' . COOKIEHASH);

I need to check whether that cookie exists or has value like below:

if(isset($_COOKIE['wordpress_logged_in_a32e4aa16e20e5346cda1']) && !empty($_COOKIE['wordpress_logged_in_a32e4aa16e20e5346cda1'])){
//do something

But now I'm working on test website and the site url is different and once I go live, site url will be changed and cookiehash also will be changed. And I don't want to have issues after going live or after going live copy and paste new hash in my functions.php file.

Is there some dynamic way to check this cookie's existence?

Answer Source

You can get the site URL variable using Wordpress function.



<?php echo get_site_url(); ?>
//Results in the full site URL being displayed:

After getting Site URL. Calculate its MD5 in PHP. Note that to use this function outside wordpress template files, You need include Worpress wp-load.php in your php code with its path.

<?php include '../../../wp-load.php'; ?>

Once MD5 is received you can concatenate string and use in your check. Let me know in comments if you have confusion.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download