php - 如何在 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>
它可以工作,但这可能会更好。仅当帖子分配了唯一的一个类别时才有效。
有任何想法吗?☺
解决方案
我可能会做的是使用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()
功能已经考虑了类别档案。
推荐阅读
- c# - 如何在 OnGUI 函数之外获取鼠标位置?
- python - 如何解决错误“列表”对象没有属性“iterdi”
- python - “包含输入脚本的目录”是什么意思?
- fabricjs - Fabric JS Unicode 问题
- c++ - 是否可以在另一个模板类上专门化模板类的方法?
- sonarqube - GitLab-CI:声纳扫描器:术语“声纳扫描器”未被识别为 cmdlet、函数的名称,
- database - Postgres SQL 更新 JDBC 卡住
- cookies - Safari 不在子域上设置 cookie
- python - 使用标准库处理 Python cidr 网络地址
- java - hibernate 不在空数据库上创建模式