首页 > 解决方案 > 如何在 Wordpress ( WP ) 中将类别定义为具有颜色值的变量?

问题描述

我在 Single.php 和 archive.php 文件中尝试这样做:

<style type="text/css">
<?php $categories = get_the_category();
$cat = $categories[0]->cat_name;
if ($cat == 'Meriendas') { ?>
    .page-title.solid-bg {background-color: #64a445!important;}
<?php }
elseif ($cat == 'Consejos') { ?>
    .page-title.solid-bg {background-color: #e62750!important;}
<?php }
else { ?>
    .page-title.solid-bg {background-color: #394299!important;}
<?php } ?>
</style>

它可以工作,但这可能会更好。仅当帖子分配了唯一的一个类别时才有效。

有任何想法吗?☺

标签: phpwordpress

解决方案


我可能会做的是使用body_class过滤器将类别添加到正文类:

add_filter( 'body_class', function( $classes ){
    if( is_single() ){
        if( $categories = get_the_category() ){
            foreach( $categories as $term ){
                $class = sanitize_html_class( $term->slug, $term->term_id );

                $classes[] = "category-$class";
            }
        }
    }

    return $classes;
});

这将做的是在单个帖子的正文中添加类,例如:category-consejos. 请注意,如果您有多个类别,它将添加多个类别,因此如果您希望一种样式覆盖另一种样式,则需要将其放在 CSS 中的较低位置。

上述功能将允许您将以下样式拖放到您的style.css文件中,外观 > 自定义 > 附加 CSS,或者甚至将它们附加到wp_add_inline_style最适合您需要的样式中。

.page-title.solid-bg {
    background-color: #394299 !important;
}

.category-meriendas .page-title.solid-bg {
    background-color: #64a445 !important;
}

.category-consejos .page-title.solid-bg {
    background-color: #e62750 !important;
}

请注意,您不需要为类别/档案添加任何特殊条件,因为该body_class()功能已经考虑了类别档案。


推荐阅读