【问题标题】:Wordpress cookie is only available from one page even though it is set for entire domainWordpress cookie 只能从一个页面获得,即使它是为整个域设置的
【发布时间】:2020-09-10 09:48:44
【问题描述】:

我在我的functions.php中设置了一个cookie,如下:

add_action('send_headers', 'sfdc_cookie');
function sfdc_cookie() {
    if( isset($_GET['sfdc']) && '' != $_GET['sfdc'] ) {
        if( empty($_COOKIE['sfdc']) ){
            if ($_GET['sfdc'] == 'mim'):
            setcookie('sfdc', 'cookievalue', time()+3156000, '/', 'www.mydomain.com' );
            //$_COOKIE['sfdc'] = 'cookie';
            endif;
        }                          
    }
    echo $_COOKIE['sfdc'];
}

如果我使用 ?sfdc=mim 访问站点上的任何页面,则会显示该值。我假设 cookie 是在那时设置的,当我从 Chrome 浏览器检查存储的 cookie 时,它​​似乎已设置。但是,如果查询字符串不存在,就好像 cookie 不存在。我什至无法将 cookie 回显到页面上。为什么当 URL 中不存在查询字符串时我无法回显该值?

我已将 add_action 从 send_headers 更改为 init,结果相同。

【问题讨论】:

  • 也许您想使用$_SESSION 变量?它对我很有用。您还可以检查session 是否已经启动,如果没有,您可以启动它,然后检查会话变量。这有帮助吗?

标签: php wordpress cookies


【解决方案1】:

你应该像这样启动这个函数:

add_action( 'wp_enqueue_scripts', 'sfdc_cookie' ); // <-- this starts the function with the same name in the location named 'wp_enqueue_scripts' 
function sfdc_cookie() {
if( isset($_GET['sfdc']) && '' != $_GET['sfdc'] ) {
    if( empty($_COOKIE['sfdc']) ){
        if ($_GET['sfdc'] == 'mim')
        {
        setcookie('sfdc', 'cookievalue', time()+3156000, '/', 'www.mydomain.com' );
        //$_COOKIE['sfdc'] = 'cookie';
        }
    }                          
}

如果您想在页面上启动 cookie 并使其在其他人中可用,您应该这样做:

add_action( 'init', 'sfdc_cookie' );
function sfdc_cookie() {
   if( !isset($_COOKIE['sfdc']) ) {
      setcookie('sfdc', 'cookievalue', time()+3156000, '/', 'www.mydomain.com' );
   }
}

【讨论】:

  • 从未在 php 中见过 endif。是wordpress 特定的东西还是什么?
  • @JonNezbit 是的,你可以在 WP 或 Laravel 中使用它,但不能这样。
  • @Kafus 您的解决方案不起作用。当我使用 wp_enqueue_scripts 而不是 send_headers 时,它似乎根本没有设置 cookie。我在测试之前清除了 cookie,它不会设置或回显。
  • @osakagreg 尝试在init 中使用它而不是在wp_enqueue_scripts - 位置init 在每个wordpress 页面上,所以它将是:add_action('init', 'sfdc_cookie')。
猜你喜欢
  • 1970-01-01
  • 2014-11-19
  • 2015-10-28
  • 2013-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-08
  • 1970-01-01
相关资源
最近更新 更多