钩子文档

display_post_states

💡 云策文档标注

概述

display_post_states 是一个 WordPress 过滤器,用于修改文章列表表中默认的文章状态显示。它允许开发者自定义或添加文章状态标签,例如草稿、置顶等。

关键要点

  • 过滤器名称:display_post_states,用于过滤文章状态数组。
  • 参数:$post_states(数组,状态slug到标签的映射)和 $post(WP_Post 对象,当前文章)。
  • 返回值:应用过滤器后的 $post_states 数组。
  • 相关函数:get_post_states() 用于从文章中检索状态数组。
  • 版本变更:5.5.0 在自定义器上下文中应用,需检查函数存在性;3.6.0 添加 $post 参数;2.8.0 引入。

代码示例

function custom_display_post_states( $states, $post ) {
    $post_status_object = get_post_status_object( $post->post_status );
    if ( in_array( $post_status_object->label, $states, true ) ) {
        return $states;
    }
    $states[ $post_status_object->name ] = $post_status_object->label;
    return $states;
}
add_filter( 'display_post_states', 'custom_display_post_states', 10, 2 );

注意事项

  • 在自定义器上下文中使用时,如果过滤器内调用管理函数,应先用 function_exists() 检查其存在性。
  • 第二个参数 $post 是 WP_Post 对象类型,而非整数。

📄 原文内容

Filters the default post display states used in the posts list table.

Parameters

string> $post_states A mapping of post state slugs to translated post state labels.
E.g. array( 'draft' => __( 'Draft' ), 'sticky' => __( 'Sticky' ), ... ).
$postWP_Post
The current post object.

Source

return apply_filters( 'display_post_states', $post_states, $post );

Changelog

Version Description
5.5.0 Also applied in the Customizer context. If any admin functions are used within the filter, their existence should be checked with function_exists() before being used.
3.6.0 Added the $post parameter.
2.8.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    This always shows the current post status in the labels. This is especially useful when adding many custom post states.

    /**
     * This always shows the current post status in the labels.
     *
     * @param array   $states current states.
     * @param WP_Post $post current post object.
     * @return array
     */
    function custom_display_post_states( $states, $post ) {
    	/* Receive the post status object by post status name */
    	$post_status_object = get_post_status_object( $post->post_status );
    
    	/* Checks if the label exists */
    	if ( in_array( $post_status_object->label, $states, true ) ) {
    		return $states;
    	}
    
    	/* Adds the label of the current post status */
    	$states[ $post_status_object->name ] = $post_status_object->label;
    
    	return $states;
    }
    
    add_filter( 'display_post_states', 'custom_display_post_states', 10, 2 );