参数
- $class
-
(string|string[]) (可选) 要添加到类列表的一个或多个类。
默认值: ''
- $post_id
-
(int|WP_Post) (可选) Post ID或Post对象。默认为全局
$post
。默认值: null
源码
更新日志
版本 | 描述 |
---|---|
2.7.0 | 开始引入 |
使用示例
添加更多类
您可以在post_class
默认值中添加一个类:<div id="post-<?php the_ID(); ?>" <?php post_class( 'class-name' ); ?>>
上面打印的HTML带有您添加的类和默认值:
<div id="post-4564" class="class-name post-4564 post type-post status-publish format-standard hentry category-news"></div>
使用数组添加多个类:
<?php $classes = array( 'class1', 'class2', 'class3', ); ?> <div id="post-<?php the_ID(); ?>" <?php post_class( $classes ); ?>>
要为非当前文章打印
post_class
CSS类,请指定其ID(整数):<?php post_class( '', 22 ); ?>
上述打印(取决于类别和标签):
class="post-22 post type-post status-publish format-standard hentry category-another-cat tag-tag1 tag-tag2
模板标签(及其默认CSS类)的示例
本例显示了主题文件(如single.php
)中常用的post_class
模板标签:<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
上述输出打印此HTML(用于“news”类别中的文章和支持文章格式的主题):
<div id="post-4564" class="class-name post-4564 post type-post status-publish format-standard hentry category-news">
然后,使用这些CSS类,您可以设置此特定文章的样式,或设置分配给相同类别(或文章格式)的所有文章的样式:
.post { /* Styles for all posts */ } .post-4564 { /* Styles for only this post (ID number 4564) */ } .category-news { /* Styles for all posts in the 'news' category */ } .format-standard { /* Styles for all posts assigned the post-format of 'standard' */ }
向
post_class
默认值添加多个类的一种简单方法是将它们作为字符串参数写入:<div <?php post_class( 'class1 class2 class3' ); ?>>
这将把这些类添加到默认类列表中。
post_class 过滤器
您也可以使用post_class过滤器添加类。