manage_posts_custom_column
云策文档标注
概述
manage_posts_custom_column 是一个 WordPress 动作钩子,用于在文章列表表的每个自定义列中触发,允许开发者自定义列内容显示。此钩子仅对非层级文章类型(如普通文章)生效,需结合 manage_{$post_type}_posts_columns 过滤器使用。
关键要点
- 钩子名称:manage_posts_custom_column,参数包括 $column_name(列名)和 $post_id(文章ID)。
- 仅适用于非层级文章类型(如 posts),层级文章类型(如 pages)应使用 manage_pages_custom_column。
- 可与 manage_{$post_type}_posts_columns 过滤器配合,添加或移除自定义列。
- WordPress 预定义了多个列名(如 'title'、'author'、'categories'),可在自定义函数中通过 switch 语句处理。
- 支持自定义文章类型,从 WP 3.1 起可使用 manage_{$post->$post_type}_posts_custom_column 针对特定类型。
代码示例
// 示例:为自定义文章类型 'books' 显示 'book_author' 和 'publisher' 列
function custom_columns( $column, $post_id ) {
switch ( $column ) {
case 'book_author':
$terms = get_the_term_list( $post_id, 'book_author', '', ',', '' );
if ( is_string( $terms ) ) {
echo $terms;
} else {
_e( 'Unable to get author(s)', 'your_text_domain' );
}
break;
case 'publisher':
echo get_post_meta( $post_id, 'publisher', true );
break;
}
}
add_action( 'manage_posts_custom_column' , 'custom_columns', 10, 2 );注意事项
- 确保正确设置钩子优先级和参数数量(如 10, 2)。
- 对于层级文章类型,避免使用此钩子,应改用 manage_pages_custom_column。
- 自定义列名需在 manage_{$post_type}_posts_columns 过滤器中定义,否则不会触发此钩子。
原文内容
Fires in each custom column in the Posts list table.
Description
This hook only fires if the current post type is non-hierarchical, such as posts.
Parameters
$column_namestring-
The name of the column to display.
$post_idint-
The current post ID.
Source
do_action( 'manage_posts_custom_column', $column_name, $post->ID );
Changelog
| Version | Description |
|---|---|
| 1.5.0 | Introduced. |
Skip to note 3 content
Steven Lin
Example Migrated from Codex:
Display Custom Post Type:
Suppose you have a ‘books’ custom post type and you want the “publisher” and “book author” to show up in the browse page.
function custom_columns( $column, $post_id ) { switch ( $column ) { case 'book_author': $terms = get_the_term_list( $post_id, 'book_author', '', ',', '' ); if ( is_string( $terms ) ) { echo $terms; } else { _e( 'Unable to get author(s)', 'your_text_domain' ); } break; case 'publisher': echo get_post_meta( $post_id, 'publisher', true ); break; } } add_action( 'manage_posts_custom_column' , 'custom_columns', 10, 2 );Skip to note 4 content
Steven Lin
Example Migrated from Codex:
Sticky Posts:
Built-in posts can be made sticky.
manage_posts_custom_columncan be used to show this in the post list./* Display custom column stickiness */ function display_posts_stickiness( $column, $post_id ) { if ($column == 'sticky'){ echo '<input type="checkbox" disabled', ( is_sticky( $post_id ) ? ' checked' : ''), '/>'; } } add_action( 'manage_posts_custom_column' , 'display_posts_stickiness', 10, 2 ); /* Add custom column to post list */ function add_sticky_column( $columns ) { return array_merge( $columns, array( 'sticky' => __( 'Sticky', 'your_text_domain' ) ) ); } add_filter( 'manage_posts_columns' , 'add_sticky_column' );