【问题标题】:Wordpress Setting a Cookie to change StylesheetWordpress 设置 Cookie 以更改样式表
【发布时间】:2020-03-30 20:16:39
【问题描述】:

我一直在尝试设置一个 cookie,它会根据单击按钮更改主题的样式表。我不知道为什么它不起作用,请有人解释我哪里出错了?

这些是我的按钮(header.php):

<a href="?style=as1" >AS1</a>
<a href="?style=as2" >AS2</a> 
<a href="?style=as3" >AS3</a>

这是我的样式表(header.php):

<link rel="stylesheet" type="text/css" media="all" id="accessible-stylesheet" href="<?php echo get_template_directory_uri(); ?>/<?php echo $stylesheet; ?>" />

这是我的函数(functions.php):

// Accessible Stylesheet Cookie

$stylesheet = "as1";

if ( isset($_GET['style']) ) {
  if ($_GET['style'] == "as2") {

    $stylesheet = "as2";

  } else if ($_GET['style'] == "as3") {

    $stylesheet = "as3";

  }

  setcookie("style","$stylesheet","3600*7");  
}

$as1stylesheet = 'css/colors-as1.css';
$as2stylesheet = 'css/colors-as2.css';
$as3stylesheet = 'css/colors-as3.css';


$stylesheet = $as1stylesheet;


if ( isset($_COOKIE['stylesheet'] ) ) {
   if ( $_COOKIE['stylesheet'] == "as2" ) {

        $stylesheet = $as2stylesheet;

    } else if ( $_COOKIE['stylesheet'] == "as3" ) {

        $stylesheet = $as3stylesheet;

    }
}

我没有收到任何错误,我无法弄清楚我哪里出错了。根本没有设置样式表。

【问题讨论】:

  • 您在操作顺序中的哪个位置设置 cookie?
  • @HowardE 你是什么意思?我错过了重要的一点吗?这是我第一次使用 cookie,如果有,请见谅。
  • 您必须在发送标头之前设置 cookie。 (如果你使用 PHP setcookie)
  • 如果我目前在 wp_head() 上方的 header.php 中拥有所有内容;对吗?
  • 是的。只是检查。

标签: php wordpress cookies


【解决方案1】:

您的 PHP 代码中有一些错误,并且错误地使用了变量。这似乎更简洁。

您不能在同一页面上设置和调用超全局 $_COOKIE。这是手册的摘录...https://www.php.net/manual/en/function.setcookie.php

一旦设置了 cookie,就可以在下一页加载时使用 $_COOKIE 数组访问它们。

$stylesheet = "as1";
// Check for cookie and set one if it's not set
if (!isset($_COOKIE['style'])) setcookie('style', $stylesheet, time() + (3600*7));

// If there is a cookie, the stylesheet is from the cookie
if ( isset($_COOKIE['style'] ) ) {
    $stylesheet = $_COOKIE['style'];
}

// If there's a get parameter set the cookie to it (for next page load), and set the stylesheet for this page load
if ( isset($_GET['style']) ) {
  $stylesheet = $_GET['style'];
  setcookie('style', $stylesheet, time() + (3600*7));
}
<link rel="stylesheet" type="text/css" media="all" id="accessible-stylesheet" href="<?php echo get_template_directory_uri(); ?>/css/colors-<?php echo $stylesheet; ?>.css" />

【讨论】:

    【解决方案2】:

    您的 cookie 名称是 style,您正在尝试检索 cookie 样式表

    setcookie("style","$stylesheet","3600*7"); 如果您只想将变量放入其中,则无需将值放在引号中: setcookie("stylesheet",$stylesheet,"3600*7");

    【讨论】:

    • 感谢您回复我,这不能解决问题吗?还是什么都没有发生?我已经尝试将所有代码放在 header.php 中,它现在显示第一个初始样式表,但在单击按钮时不会改变?
    猜你喜欢
    • 2021-02-13
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 1970-01-01
    • 2019-04-11
    • 2014-12-14
    • 2017-11-13
    相关资源
    最近更新 更多