Wordpress/PHP - 当存在 URL 参数时加载样式表

Wordpress/PHP - load stylesheet when URL parameter is present

希望找到一种方法,使 Wordpress 站点仅在存在 URL 参数时才加载样式表。例如当 http://www.somesite.com is loaded, it will use whatever stylesheets are in use by the theme. But if a specific URL parameter is used, an additional stylesheet will be called. Example http://www.somesite.com?useAltCss=yes。在这种情况下,在主题样式表之后加载一个额外的样式表。这让我有机会仅在使用 URL 参数时覆盖主题样式,并测试 style/laylout 更改而不影响 public 查看。

我假设 header.php 需要修改编码。以下不工作 PHP 语法,但让您了解我正在寻找:

<?php
    $param = ($_GET["useAltCss"]);
    if($param == 'yes') {
        <link rel="stylesheet" type="text/css" href="custom.css" />
    } else {
        // Do nothing
    }
?>

更新:

看起来我的原始代码很接近我只需要更改第 4 行:

<link rel="stylesheet" type="text/css" href="custom.css" />

至:

echo('<link rel="stylesheet" type="text/css" href="custom.css" />');

虽然这行得通,但我想知道是否有更有效的方法来做到这一点。如果我导航到新页面以测试样式更改,我必须手动添加 URL 参数。如果它以某种方式锁定在 custom.css 样式表中,那就太好了……也许使用 cookie 或会话?我想知道如何切换它 on/off。想法?

如果您只是自己使用它,那么我认为您的方法很好...但是 - 对于其他遇到这个问题的人 - 我想强调的是,这 不是 做事按部就班。下面建议的第二种方法是一个不错的解决方案,但第一种方法只能用于非常临时的情况(在每次页面加载时打开 session 可能是不必要的,并且会导致性能下降)。

样式表也不应手动打印(即使用 <link[...]>),而是在 wp_enqueue_scripts 挂钩中使用 wp_enqueue_style()

方法一

要保留 "setting" 而不是必须在每次加载页面时手动键入它,您可以使用 session ,如下所示:

你需要在headers发送之前打开一个session,所以把这个放在wp-config.php:

//Start the session if it isn't already
session_start();

其余的放在您想要样式表的任何地方(很可能在 header.php 中):

//Check if the parameter is set
if (isset($_GET["useAltCss"])) {
    if($_GET["useAltCss"] === 'yes') {
        //Adjust the session
        $_SESSION['useAltCss'] = true;
    } else {
        /**
         * If set to anything other than "yes", assume it's being switched
         * off, and adjust the session
         */
        $_SESSION['useAltCss'] = false;
    }
}
//Check if the session variable exists, and is currently true
if (isset($_SESSION['useAltCss']) && $_SESSION['useAltCss'] === true) {
    //And print your stylesheet
    echo '<link rel="stylesheet" type="text/css" href="custom.css" />';
}

方法二

另一个(更简单的)选项是简单地检查当前用户是否登录并能够编辑主题(我希望你这样做):

if (current_user_can('edit_themes')) {
    echo '<link rel="stylesheet" type="text/css" href="custom.css" />';
}

...这当然不允许您来回切换 - 除非每次都登录和退出。