当前浏览:首页 / WordPress钩子 / post_class

apply_filters( 'post_class', string[] $classes, string[] $class, int $post_id )

过滤当前文章的CSS类名列表

class

postmore...


参数

$classes

(string[]) 文章CSS类名称的数组。

$class

(string[]) 添加到文章的附加类名数组。

$post_id

(int) 文章ID。



源码

查看源码 官方文档


更新日志

版本描述
2.7.0开始引入

使用示例

  • 示例1

    用于文章表行的自定义类。

    此过滤器可用于向仪表板的任何edit.php页面中的文章行添加其他类,

    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

    当调用函数get_post_class($class, $post_id)时,将调用过滤器。在函数结束时调用。
    在内部,WordPress将在许多地方调用此函数,包括管理仪表板页面。过滤器允许您过滤将添加到页面的数组$classes
    此外,通过插件或模板传递给函数调用的类将作为第二个参数$class传递,最后第三个参数是函数正在处理的post对象的ID。