最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

headers - set cookies on certain page only

programmeradmin1浏览0评论

I am trying to set a cookie on Wordpress on a certain page only. I've tried a LOT of different ideas but still can't get it to work as 'init' is called before the page is set.

This is my current code:

add_action('init', function() { 
    //if ( is_page( 2164 ) ) {  
        setcookie( "my_cookie", 'hello' );
    }
});

But of course is_page() won't return the current page and nor does anything else I try.

I've looked at other suggestions on StackExchange (e.g. using 'templateredirect') but they don't work for me either.

So has anyone any idea how I can set a cookie when a user hits a certain page only?

Thanks!

I am trying to set a cookie on Wordpress on a certain page only. I've tried a LOT of different ideas but still can't get it to work as 'init' is called before the page is set.

This is my current code:

add_action('init', function() { 
    //if ( is_page( 2164 ) ) {  
        setcookie( "my_cookie", 'hello' );
    }
});

But of course is_page() won't return the current page and nor does anything else I try.

I've looked at other suggestions on StackExchange (e.g. using 'templateredirect') but they don't work for me either.

So has anyone any idea how I can set a cookie when a user hits a certain page only?

Thanks!

Share Improve this question asked Nov 5, 2019 at 9:45 arathraarathra 451 gold badge1 silver badge3 bronze badges 1
  • 1 Are you very, very sure hooks like wp and template_redirect do not work? And btw, it's not "templateredirect". – Sally CJ Commented Nov 5, 2019 at 9:50
Add a comment  | 

1 Answer 1

Reset to default 0

Please try to create certain page template and set cookies

<?php
/*
    Template Name: Certain Page
*/

setcookie('my_cookie', "hello", (time()+3600), "/");
get_header(); 
?>
发布评论

评论列表(0)

  1. 暂无评论