How to read WordPress cookies on my website?

I want to integrate my site with wordpress. I want to know how I can read WordPress cookies, so I don’t need to authenticate users on my site again. I tried to include the wordpress header file on my website, but then I could not connect to the database of my website. Both of them are different. Can I set advanced cookie options like user level etc. My site is written in php.

+6
source share
2 answers

On your website, include this code at the top of each file:

<?php define('WP_USE_THEMES', false); require('./blog/wp-blog-header.php'); ?> 

... if your blog is at ./blog/ .

It includes the entire wordpress stack. You will have access to all the wordpress features in your code. Thanks to this, you can easily check if the user is registered, roles and features, but also retrieve messages or so.

Then in your code to check the user:

 if (is_user_logged_in()) { ... } 

Code: is_user_logged_in ()

You can also specify a link to exit:

 <a href="<?php bloginfo("url"); ?>/wp-login.php?action=logout/">Logout</a> 

If your blog and your site are not in the same domain or subdomain, you need to configure the cookie domain in wp-config.php

 define('COOKIE_DOMAIN', '.domain.com'); // Share cookie on all subdomains 

EDIT

If you really want to read Wordpress cookies (which is a good choice for performance): the cookie name is stored in the AUTH_COOKIE constant.

AUTH_COOKIE is defined in /wp-includes/default-constants.php -> line 171 as

 "wordpress_" + md5( get_site_option(siteurl) ) 

You should get or recount AUTH_COOKIE, then read $ _COOKIE [AUTH_COOKIE].

To analyze it, look at wp_parse_auth_cookie() in wp-includes/pluggable.php @line 585 (indeed, the format is simple user|expiration|hmac , so we divide the chain by | and get the first element)

+4
source

For cookies to work in Wordpress, you need to set it in a special way in 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'); 

So, the important point is setcookie('sitename_newvisitor', 1, time()+1209600, COOKIEPATH, COOKIE_DOMAIN, false);

To get it

 if (isset($_COOKIE['sitename_newvisitor'])) { echo 'Welcome back!'; } else { echo 'Hello new visitor!'; } 

Note You can change the cookie name "sitename_newvisitor", value, timeout, COOKIEPATH and COOKIE_DOMAIN to suit your needs.

-1
source

Source: https://habr.com/ru/post/908832/


All Articles