钩子文档

post_class

💡 云策文档标注

概述

post_class 是一个 WordPress 过滤器,用于修改当前文章的 CSS 类名列表。它允许开发者在文章容器元素上动态添加或移除类名,常用于前端样式定制或后台管理界面增强。

关键要点

  • 过滤器名称:post_class
  • 参数:$classes(文章类名数组)、$css_class(额外类名数组)、$post_id(文章 ID)
  • 调用时机:在 get_post_class() 函数内部调用,适用于前端和后台页面
  • 用途:可基于文章属性、元数据或上下文条件添加自定义类

代码示例

add_filter('post_class', 'set_row_post_class', 10, 3);
function set_row_post_class($classes, $class, $post_id){
    if (!is_admin()) {
        return $classes;
    }
    $screen = get_current_screen();
    if ('my-custom-type' != $screen->post_type && 'edit' != $screen->base) {
        return $classes;
    }
    $profile_incomplete = get_post_meta($post_id, 'profile_incomplete', true);
    if ('yes' == $profile_incomplete) {
        $classes[] = 'profile_incomplete';
    }
    return $classes;
}

注意事项

  • 确保在 is_admin() 检查中处理后台逻辑,避免影响前端输出
  • 使用 get_current_screen() 验证当前页面,以精确控制类添加范围
  • 过滤器从 WordPress 2.7.0 版本引入,兼容性良好

📄 原文内容

Filters the list of CSS class names for the current post.

Parameters

$classesstring[]
An array of post class names.
$css_classstring[]
An array of additional class names added to the post.
$post_idint
The post ID.

Source

$classes = apply_filters( 'post_class', $classes, $css_class, $post->ID );

Changelog

Version Description
2.7.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    Custom classes for post table rows.

    This filter can be used to add additional classes to the rows of post in any edit.php post page of the dashboard,

    add_filter('post_class', 'set_row_post_class', 10,3);
    function set_row_post_class($classes, $class, $post_id){
        if (!is_admin()) { //make sure we are in the dashboard 
            return $classes;
        }
        $screen = get_current_screen(); //verify which page we're on
        if ('my-custom-type' != $screen->post_type && 'edit' != $screen->base) {
            return $classes;
        }
        //check if some meta field is set 
        $profile_incomplete = get_post_meta($post_id, 'profile_incomplete', true);
        if ('yes' == $profile_incomplete) {
            $classes[] = 'profile_incomplete'; //add a custom class to highlight this row in the table
        }
    
        // Return the array
        return $classes;
    }

  2. Skip to note 4 content

    The filter is called when ever the function get_post_class($class, $post_id) is called. It is called at the end of the of function.
    Internally WordPress will call this function in many places, including the admin dashboard pages. The filter allows you to filter the Array $classes which will be added to the page.
    Furthermore, the classes passed to the function call by say a plugin or a template will be passed as the 2nd parameter $class, and finally the third parameter is the ID of the post object being processed by the function.