钩子文档

list_table_primary_column

💡 云策文档标注

概述

list_table_primary_column 是一个 WordPress 过滤器,用于修改当前列表表的主列名称。它允许开发者根据屏幕 ID 自定义主列,以优化列表布局和样式。

关键要点

  • 过滤器名称为 list_table_primary_column,用于过滤列表表的主列名称。
  • 接受两个参数:$default(默认主列名称,如 'name')和 $context(屏幕 ID,如 'plugins')。
  • 在 WP_List_Table::get_primary_column_name() 方法中调用,影响列表表的 CSS 样式和布局。
  • 从 WordPress 4.3.0 版本引入,适用于用户表、自定义文章类型等列表。

代码示例

function my_list_table_primary_column( $default, $screen ) {
    // 在 Users 屏幕上设置 'Name' 列为主列
    if ( 'users' === $screen ) {
        $default = 'name';
    }
    
    // 为自定义文章类型设置主列
    if ( 'edit-my_custom_post_type' === $screen ) {
        $default = 'my_custom_column_name';
    }
    
    return $default;
}
add_filter( 'list_table_primary_column', 'my_list_table_primary_column', 10, 2 );

注意事项

  • 设置主列时,需确保列存在,否则可能导致布局问题。
  • WordPress 对主列之后的列应用特定 CSS 规则,如 .wp-list-table tr:not(.inline-edit-row):not(.no-items) td.column-primary~td:not(.check-column),以保持样式一致。
  • 建议结合其他钩子(如 manage_post_type_posts_columns)进行列管理。

📄 原文内容

Filters the name of the primary column for the current list table.

Parameters

$defaultstring
Column name default for the specific list table, e.g. 'name'.
$contextstring
Screen ID for specific list table, e.g. 'plugins'.

Source

$column = apply_filters( 'list_table_primary_column', $default, $this->screen->id );

Changelog

Version Description
4.3.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    A simple example for Users table and CPT table

    function my_list_table_primary_column( $default, $screen ) {//                                                             Alter the primary column in edit.php table(s)
    
    	// if we want the 'Name' column to be the primary column, on Users screen
        if ( 'users' === $screen ) {
            $default = 'name';
        }
        
    	// if we want to set the primary column for CPT
        if ( 'edit-my_custom_post_type' === $screen ) {
            $default = 'my_custom_column_name';
        }
        
        return $default;
    }
    add_filter( 'list_table_primary_column', 'my_list_table_primary_column', 10, 2 );

    For further management of columns, check:

    https://developer.wordpress.org/reference/hooks/manage_post_type_posts_columns/
    To add/remove/rename columns

    https://developer.wordpress.org/reference/hooks/manage_post-post_type_posts_custom_column/
    To set the custom column values

  2. Skip to note 4 content

    If you’re adding a column in the first position, it’s important to set this column as primary because WordPress has CSS rules that are applied for columns after the primary column. Otherwise, the list table can render with some layout issues.

    Example of CSS rule used by WordPress:

    .wp-list-table tr:not(.inline-edit-row):not(.no-items) td.column-primary~td:not(.check-column)