函数文档

get_column_headers()

💡 云策文档标注

概述

get_column_headers() 函数用于获取指定屏幕的列标题,返回以列ID为键的标签数组。它通过静态缓存优化性能,并支持通过过滤器动态修改列标题。

关键要点

  • 参数 $screen 可以是字符串或 WP_Screen 对象,用于指定目标屏幕。
  • 返回值为字符串数组,键为列ID,值为列标题标签。
  • 内部使用静态变量 $column_headers 缓存结果,避免重复计算。
  • 通过 apply_filters() 应用 manage_{$screen->id}_columns 过滤器,允许开发者自定义列标题。
  • 函数首先将字符串参数转换为 WP_Screen 对象,确保兼容性。

代码示例

function get_column_headers( $screen ) {
    static $column_headers = array();

    if ( is_string( $screen ) ) {
        $screen = convert_to_screen( $screen );
    }

    if ( ! isset( $column_headers[ $screen->id ] ) ) {
        $column_headers[ $screen->id ] = apply_filters( "manage_{$screen->id}_columns", array() );
    }

    return $column_headers[ $screen->id ];
}

注意事项

  • 过滤器 manage_{$screen->id}_columns 是动态的,例如编辑文章屏幕的过滤器为 manage_edit-post_columns。
  • 函数自 WordPress 2.7.0 版本引入,相关函数包括 convert_to_screen() 和 apply_filters()。
  • 常用于 WP_List_Table 相关类中,如获取列信息或渲染列首选项。

📄 原文内容

Get the column headers for a screen

Parameters

$screenstring|WP_Screenrequired
The screen you want the headers for

Return

string[] The column header labels keyed by column ID.

Source

function get_column_headers( $screen ) {
	static $column_headers = array();

	if ( is_string( $screen ) ) {
		$screen = convert_to_screen( $screen );
	}

	if ( ! isset( $column_headers[ $screen->id ] ) ) {
		/**
		 * Filters the column headers for a list table on a specific screen.
		 *
		 * The dynamic portion of the hook name, `$screen->id`, refers to the
		 * ID of a specific screen. For example, the screen ID for the Posts
		 * list table is edit-post, so the filter for that screen would be
		 * manage_edit-post_columns.
		 *
		 * @since 3.0.0
		 *
		 * @param string[] $columns The column header labels keyed by column ID.
		 */
		$column_headers[ $screen->id ] = apply_filters( "manage_{$screen->id}_columns", array() );
	}

	return $column_headers[ $screen->id ];
}

Hooks

apply_filters( “manage_{$screen->id}_columns”, string[] $columns )

Filters the column headers for a list table on a specific screen.

Changelog

Version Description
2.7.0 Introduced.