函数文档

_post_states()

💡 云策文档标注

概述

_post_states() 函数用于获取并输出文章状态的 HTML 字符串,支持通过参数控制是否直接显示或返回字符串。它基于 get_post_states() 获取状态数组,并应用过滤器 post_states_html 进行自定义。

关键要点

  • 函数接受两个参数:$post(必需,WP_Post 对象)和 $display(可选,布尔值,默认为 true 表示直接输出)。
  • 返回值为文章状态的 HTML 字符串,例如 "— Draft, Sticky"。
  • 内部使用 get_post_states() 获取状态数组,并通过循环构建带分隔符的 HTML 字符串。
  • 提供过滤器 post_states_html,允许开发者修改输出的 HTML 字符串。
  • 自 WordPress 5.3.0 起添加了 $display 参数和返回值功能。

代码示例

function _post_states( $post, $display = true ) {
	$post_states      = get_post_states( $post );
	$post_states_html = '';

	if ( ! empty( $post_states ) ) {
		$state_count = count( $post_states );

		$i = 0;

		$post_states_html .= ' — ';

		foreach ( $post_states as $state ) {
			++$i;

			$separator = ( $i < $state_count ) ? ', ' : '';
			$post_states_html .= "<span class="post-state">{$state}{$separator}</span>";
		}
	}

	$post_states_html = apply_filters( 'post_states_html', $post_states_html, $post_states, $post );

	if ( $display ) {
			echo $post_states_html;
	}

	return $post_states_html;
}

注意事项

  • 函数主要用于后台文章列表等场景,如 WP_Posts_List_Table::column_title() 中使用。
  • 确保传入有效的 WP_Post 对象以避免错误。
  • 过滤器 post_states_html 的参数包括 HTML 字符串、状态数组和文章对象,便于自定义输出。

📄 原文内容

Echoes or returns the post states as HTML.

Description

See also

Parameters

$postWP_Postrequired
The post to retrieve states for.
$displaybooloptional
Whether to display the post states as an HTML string.

Default:true

Return

string Post states string.

Source

function _post_states( $post, $display = true ) {
	$post_states      = get_post_states( $post );
	$post_states_html = '';

	if ( ! empty( $post_states ) ) {
		$state_count = count( $post_states );

		$i = 0;

		$post_states_html .= ' — ';

		foreach ( $post_states as $state ) {
			++$i;

			$separator = ( $i < $state_count ) ? ', ' : '';

			$post_states_html .= "<span class='post-state'>{$state}{$separator}</span>";
		}
	}

	/**
	 * Filters the HTML string of post states.
	 *
	 * @since 6.9.0
	 *
	 * @param string                 $post_states_html All relevant post states combined into an HTML string for display.
	 *                                                 E.g. `— <span class='post-state'>Draft, </span><span class='post-state'>Sticky</span>`.
	 * @param array<string, string>  $post_states      A mapping of post state slugs to translated post state labels.
	 *                                                 E.g. `array( 'draft' => __( 'Draft' ), 'sticky' => __( 'Sticky' ), ... )`.
	 * @param WP_Post                $post             The current post object.
	 */
	$post_states_html = apply_filters( 'post_states_html', $post_states_html, $post_states, $post );

	if ( $display ) {
		echo $post_states_html;
	}

	return $post_states_html;
}

Hooks

apply_filters( ‘post_states_html’, string $post_states_html, array<string, , WP_Post $post )

Filters the HTML string of post states.

Changelog

Version Description
5.3.0 Added the $display parameter and a return value.
2.7.0 Introduced.