函数文档

post_class()

💡 云策文档标注

概述

post_class() 是一个 WordPress 模板函数,用于输出文章容器的 CSS 类属性。它基于文章属性(如 ID、类型、状态、分类等)生成默认类,并允许开发者添加自定义类。

关键要点

  • 函数作用:输出文章容器的 class 属性,包含默认类(如 post-ID、type-post、category-* 等)和自定义类。
  • 参数说明:$css_class 参数接受字符串或数组,用于添加额外类;$post 参数指定文章 ID 或 WP_Post 对象,默认为全局 $post。
  • 内部实现:调用 get_post_class() 获取类数组,使用 esc_attr() 转义后输出。
  • 使用场景:常用于主题模板文件(如 single.php)中,为文章元素提供样式钩子。
  • 扩展方式:可通过 post_class 过滤器动态添加或修改类。

代码示例

<div <?php post_class(); ?>>
    <!-- 文章内容 -->
</div>

<?php post_class('custom-class'); ?>

<?php post_class(array('class1', 'class2')); ?>

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

注意事项

  • 函数直接输出 HTML 属性,需在模板中适当位置调用。
  • 默认类基于文章属性自动生成,有助于主题样式定制。
  • 使用 $post 参数可针对非当前文章输出类。

📄 原文内容

Displays the classes for the post container element.

Parameters

$css_classstring|string[]optional
One or more classes to add to the class list.
Default empty.
$postint|WP_Postoptional
Post ID or post object. Defaults to the global $post.

Default:null

Source

function post_class( $css_class = '', $post = null ) {
	// Separates classes with a single space, collates classes for post DIV.
	echo 'class="' . esc_attr( implode( ' ', get_post_class( $css_class, $post ) ) ) . '"';
}

Changelog

Version Description
2.7.0 Introduced.

User Contributed Notes

  1. Skip to note 6 content

    Add more classes.
    You can add a class to the post_class defaults:

    <div id="post-<?php the_ID(); ?>" <?php post_class( 'class-name' ); ?>>

    The above prints HTML with your added class and the defaults:
    [html]

    [/html]

    Use an array to add multiple classes:

    
    
    <div id="post-<?php the_ID(); ?>" <?php post_class( $classes ); ?>>

  2. Skip to note 8 content

    Example of the template tag (and its default CSS classes).
    This example shows the post_class template tag as commonly used in a theme file (such as single.php):

    <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

    The output of the above prints this HTML (for a post in the ‘news’ category and a theme that supports Post Formats):
    [html]

    [/html]

    Using these CSS classes you can then style this specific post, or all posts assigned the same category (or post format):

    .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'  */
    }

You must log in before being able to contribute a note or feedback.

{“prefetch”:[{“source”:”document”,”where”:{“and”:[{“href_matches”:”/*”},{“not”:{“href_matches”:[“/wp-*.php”,”/wp-admin/*”,”/files/*”,”/wp-content/*”,”/wp-content/plugins/*”,”/wp-content/themes/wporg-developer-2023/*”,”/wp-content/themes/wporg-parent-2021/*”,”/*\?(.+)”]}},{“not”:{“selector_matches”:”a[rel~=”nofollow”]”}},{“not”:{“selector_matches”:”.no-prefetch, .no-prefetch a”}}]},”eagerness”:”conservative”}]}

var prism_settings = {“pluginUrl”:”https://developer.wordpress.org/wp-content/plugins/code-syntax-block/”};
//# sourceURL=mkaz-code-syntax-prism-js-js-extra

var autocomplete = {“ajaxurl”:”https://developer.wordpress.org/wp-admin/admin-ajax.php”,”nonce”:”dc6f8fe9ee”,”post_type”:”wp-parser-function”};
//# sourceURL=autocomplete-js-extra

wp.i18n.setLocaleData( { ‘text directionu0004ltr’: [ ‘ltr’ ] } );
//# sourceURL=wp-i18n-js-after

var wporgFunctionReferenceI18n = {“copy”:”Copy”,”copied”:”Code copied”,”expand”:”Expand code”,”collapse”:”Collapse code”,”sourceFile”:”wp-includes/post-template.php”};
//# sourceURL=wporg-developer-function-reference-js-extra

var quicktagsL10n = {“closeAllOpenTags”:”Close all open tags”,”closeTags”:”close tags”,”enterURL”:”Enter the URL”,”enterImageURL”:”Enter the URL of the image”,”enterImageDescription”:”Enter a description of the image”,”textdirection”:”text direction”,”toggleTextdirection”:”Toggle Editor Text Direction”,”dfw”:”Distraction-free writing mode”,”strong”:”Bold”,”strongClose”:”Close bold tag”,”em”:”Italic”,”emClose”:”Close italic tag”,”link”:”Insert link”,”blockquote”:”Blockquote”,”blockquoteClose”:”Close blockquote tag”,”del”:”Deleted text (strikethrough)”,”delClose”:”Close deleted text tag”,”ins”:”Inserted text”,”insClose”:”Close inserted text tag”,”image”:”Insert image”,”ul”:”Bulleted list”,”ulClose”:”Close bulleted list tag”,”ol”:”Numbered list”,”olClose”:”Close numbered list tag”,”li”:”List item”,”liClose”:”Close list item tag”,”code”:”Code”,”codeClose”:”Close code tag”,”more”:”Insert Read More tag”};
//# sourceURL=quicktags-js-extra

var wporg_note_feedback = {“show”:”Show feedback”,”hide”:”Hide feedback”,”hide_feedback”:”Hide feedback form”,”add_feedback”:”Add feedback”};
//# sourceURL=wporg-developer-user-notes-feedback-js-extra

var wporg_note_preview = {“ajaxurl”:”https://developer.wordpress.org/wp-admin/admin-ajax.php”,”nonce”:”119215fa41″,”preview”:”preview note”,”preview_empty”:”Nothing to preview”,”is_admin”:””};
//# sourceURL=wporg-developer-preview-js-extra

_stq = window._stq || [];
_stq.push([ “view”, {“v”:”ext”,”blog”:”209306761″,”post”:”1404″,”tz”:”0″,”srv”:”developer.wordpress.org”,”j”:”1:15.5″} ]);
_stq.push([ “clickTrackerInit”, “209306761”, “1404” ]);
//# sourceURL=jetpack-stats-js-before

var wporgGlobalHeaderI18n = {“openSearchLabel”:”Open Search”,”closeSearchLabel”:”Close Search”,”overflowMenuLabel”:”More menu”};
//# sourceURL=wporg-global-header-script-js-extra

{“baseUrl”:”https://s.w.org/images/core/emoji/17.0.2/72×72/”,”ext”:”.png”,”svgUrl”:”https://s.w.org/images/core/emoji/17.0.2/svg/”,”svgExt”:”.svg”,”source”:{“concatemoji”:”https://developer.wordpress.org/wp-includes/js/wp-emoji-release.min.js?ver=7.1-alpha-62239″}}

/*! This file is auto-generated */
const a=JSON.parse(document.getElementById(“wp-emoji-settings”).textContent),o=(window._wpemojiSettings=a,”wpEmojiSettingsSupports”),s=[“flag”,”emoji”];function i(e){try{var t={supportTests:e,timestamp:(new Date).valueOf()};sessionStorage.setItem(o,JSON.stringify(t))}catch(e){}}function c(e,t,n){e.clearRect(0,0,e.canvas.width,e.canvas.height),e.fillText(t,0,0);t=new Uint32Array(e.getImageData(0,0,e.canvas.width,e.canvas.height).data);e.clearRect(0,0,e.canvas.width,e.canvas.height),e.fillText(n,0,0);const a=new Uint32Array(e.getImageData(0,0,e.canvas.width,e.canvas.height).data);return t.every((e,t)=>e===a[t])}function p(e,t){e.clearRect(0,0,e.canvas.width,e.canvas.height),e.fillText(t,0,0);var n=e.getImageData(16,16,1,1);for(let e=0;e{s[e]=t(o,e,n,a)}),s}function r(e){var t=document.createElement(“script”);t.src=e,t.defer=!0,document.head.appendChild(t)}a.supports={everything:!0,everythingExceptFlag:!0},new Promise(t=>{let n=function(){try{var e=JSON.parse(sessionStorage.getItem(o));if(“object”==typeof e&&”number”==typeof e.timestamp&&(new Date).valueOf(){i(n=e.data),r.terminate(),t(n)})}catch(e){}i(n=f(s,u,c,p))}t(n)}).then(e=>{for(const n in e)a.supports[n]=e[n],a.supports.everything=a.supports.everything&&a.supports[n],”flag”!==n&&(a.supports.everythingExceptFlag=a.supports.everythingExceptFlag&&a.supports[n]);var t;a.supports.everythingExceptFlag=a.supports.everythingExceptFlag&&!a.supports.flag,a.supports.everything||((t=a.source||{}).concatemoji?r(t.concatemoji):t.wpemoji&&t.twemoji&&(r(t.twemoji),r(t.wpemoji)))});
//# sourceURL=https://developer.wordpress.org/wp-includes/js/wp-emoji-loader.min.js