当前浏览:首页 / WordPress函数 / post_class()

post_class( string|string[] $class = '', int|WP_Post $post_id = null )

显示post容器元素的类

class

postmore...


参数

$class

(string|string[]) (可选) 要添加到类列表的一个或多个类。

默认值: ''

$post_id

(int|WP_Post) (可选) Post ID或Post对象。默认为全局$post

默认值: null



源码

查看源码 官方文档


更新日志

版本描述
2.7.0开始引入

使用示例

  • 示例1

    添加更多类
    您可以在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 ); ?>>
    
  • 示例2

    要为非当前文章打印post_classCSS类,请指定其ID(整数):

    <?php post_class( '', 22 ); ?>

    上述打印(取决于类别和标签):
    class="post-22 post type-post status-publish format-standard hentry category-another-cat tag-tag1 tag-tag2

  • 示例3

    模板标签(及其默认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'  */
    }
    
  • 示例4

    post_class默认值添加多个类的一种简单方法是将它们作为字符串参数写入:

    <div <?php post_class( 'class1 class2 class3' ); ?>>
    

    这将把这些类添加到默认类列表中。

  • 示例5

    post_class 过滤器
    您也可以使用post_class过滤器添加类。