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条)

报告相同问题?

悬赏问题

  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划