doutan8775 2014-12-14 18:58
浏览 73
已采纳

有条件地在Wordpress中打印CSS样式

I am working on a Wordpress theme and want to give the option to choose between a boxed layout and a full width layout.

For this purpose I created a variable in my header.php:

<head>
    <?php
        $isBoxedLayout = true;
    ?>
...
</head>

Down in the body I am asking if the variable is set:

<?php if($isBoxedLayout) { echo '<div id="boxed">'; } ?>
...
<?php if($isBoxedLayout) { echo '</div>'; } ?>

This works fine so far. But now I also want to change some css styles if this variable is set. My problem is that I am not so good in PHP yet so my solution would be something like this:

<head>
    <?php
        $isBoxedLayout = true;
    ?>
    ...
    if ($isBoxedLayout) {
        echo '<style type="text/css">';
        echo '#container {width:999px;}';
        echo '</style>';
    }
</head>

But I think this is not good programming because my header.php file would soon be full of code and confusing if I would add some other options. So logically I should create a variable or an array maybe in the functions.php file and outsource my code like this:

$isBoxedLayout = true;

if ($isBoxedLayout) {
    function boxed_css_styles() {
        echo '<style type="text/css">';
        echo '#container {width:999px;}';
        echo '</style>';
    }
}

Is my thinking right? And if so how would I access the functions I create in my index.php or header.php or whatever. Or would it work to print the styles in the functions.php?

best regards

  • 写回答

2条回答 默认 最新

  • dongmeba4877 2014-12-14 19:08
    关注

    Don't over-complicate this by trying to add styles via PHP. Add the ID via PHP...but not the styles themselves.

    Since you only apply the boxed ID when the boxed layout is in effect, you can simply define some #boxed CSS styles. These styles will ONLY be applied if the ID exists in your markup...which means they won't come into effect when the ID isn't applied by your PHP.

    In other words, put this in your CSS stylesheet, and forget about it:

    #boxed {
        width: 999px;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试