如果是某个类别,使用不同的 CSS class

If certain category, use different CSS class

我对自定义 wordpress 开发完全陌生。我的文章页面包含三个可能的 post 类别。

我需要一个 If, Else If, Else 语句来允许我更改类别标题栏的配色方案。前任。如果类别 1,使用 class 'blue' 否则如果类别 2,使用 class 'red',否则 class 'yellow'.

我 运行 遇到的问题是我在类别和图像 url.

的 if else 语句中有 php

请指教。谢谢

<div class="col-xs-12 col-md-3 ">
    <!--Check category for color scheme -->
<?php if ( in_category( 'Data Governance' )) { ?>
    <div class="categoryHeading blue">
        <?php query_posts('category_name=Data Governance'); 
            if (have_posts()) : while (have_posts()) : the_post(); ?>
                <div class="row">
                    <div class="col-md-2 hidden-xs">
                        <img src="<?php bloginfo('template_url'); ?>/img/category_icon.png">
                    </div>
                    <div class="col-md-10">
                        <h1 class="toUpper"><?php the_category(', '); ?></h1>
                    </div>
                </div>                                  
    </div>
</div>
<?php endwhile; endif; wp_reset_query();?>
<?php }?>

这取决于其他代码根据类别更改了多少。如果只有 div 颜色,你可以这样做:

    <?php
    if ($category=="category 1")
        $divColor="blue";
    elseif ($category=="category 2")
        $divColor="red";
    else
        $divColor="yellow";

    echo "<div class=\"$divColor\">";
    ?>

否则您可能需要设置更多变量,或者可能需要将整个部分包含三次,使用相同的 if、elseif、else 语句。

您可以尝试这样的操作:

<?php
$cat_colors = array();
$cat_colors['cat1'] = 'blue';
$cat_colors['cat2'] = 'red';
$cat_colors['cat3'] = 'yellow';
$categories = get_the_category();
?>

...跳过很多内容...

 <div class="categoryHeading <?php echo $cat_colors[$categories[0]->slug;?>">

这假设您已经为每个 post 分配了一个类别...或者您至少只对第一个类别感兴趣。 数组中的 cat1、cat2、cat3 指的是类别 slugs。

HTH,

=C=