Reputation: 1429
Here is my code:
function set_newuser_cookie() {
if ( !is_admin() && !isset($_COOKIE['domain_newvisitor'])) {
setcookie('domain_newvisitor', 1, time()+3600*24*100, '/', 'domain.com', false);
}
}
add_action( 'init', 'set_newuser_cookie');
With this code cookie works well but when am checking cookie existance via this javascript code (need to check whether we have cookie or not to use it somewhere else in javascript code):
var isCookie = document.cookie.match(/^(.*;)?domain_newvisitor=[^;]+(.*)?$/);
if(isCookie){
console.log('yes');
}else{
console.log('no');
}
it always shows 'yes' in console log, even when am deleting cookie and visiting website first time. How can I change php code to create cookie only when user will open page second time.
Upvotes: 1
Views: 764
Reputation: 5466
You are setting the cookie as:
function set_newuser_cookie() {
if ( !is_admin() && !isset($_COOKIE['domain_newvisitor'])) {
setcookie('domain_newvisitor', 1, time()+3600*24*100, '/', 'domain.com', false);
}
}
add_action( 'init', 'set_newuser_cookie');
Explanation: If the cookie is set already => !isset($_COOKIE['domain_newvisitor'])
and user is not admin you are setting cookie.
After this it is being checked it the cookie exits :
var isCookie = document.cookie.match(/^(.*;)?domain_newvisitor=[^;]+(.*)?$/);
if(isCookie){
console.log('yes');
}else{
console.log('no');
}
Then the cookie will exits every time. As you are creating it if it is first time and checking if it exits.
You should check if cookie exits then store it variable and use it of not then create it:
function set_newuser_cookie() {
if ( !is_admin() && !isset($_COOKIE['domain_newvisitor'])) {
setcookie('domain_newvisitor', 1, time()+3600*24*100, '/', 'domain.com', false);
}else
if(!is_admin() && isset($_COOKIE['domain_newvisitor'])){
$CookieValue = $_COOKIE['domain_newvisitor']
//echo or return this $CookieValue
}
}
add_action( 'init', 'set_newuser_cookie');
Now You can use $CookieValue in js by passing it from server to client.
Upvotes: 1