Once logged into the WP admin, I can refresh the front-end and see my cookie’s value outputted as “hello world”. If I log out of the admin, then refresh my front-end, the cookie’s value is now “nothing”, as seen in my example function.
This only happens when I’m viewing the website online. When testing locally, I can read the cookie without being logged into the WP admin. Any ideas?
Here’s my test function for setting the cookie
function test_cookie() {
setcookie( 'test-cookie', 'hello world', time()+1209600, '/');
}
add_action( 'init', 'test_cookie' );
Here’s the function for outputting the cookie’s value onto the page
function output_test_cookie() {
if ( isset( $_COOKIE['test-cookie'] ) )
echo $_COOKIE["test-cookie"]; // should output hello world, but only does this when logged into WP admin
else
echo 'nothing';
}
add_action( 'template_redirect', 'output_test_cookie' );
It appears I needed to use an earlier hook. Using the
wp
orinit
action hooks allow me to read the cookie’s value without logging into the admin first.