
如上图,在 WordPress 后台,文章列表默认会展示一些列,像标题、日期等。有时候想要添加其他信息至列表中,这时可以用过滤器manage_posts_columns和manage_posts_custom_column动作,能够添加、移除或者重新排列这些列,把其显示文章列表,以此满足特定的需求。以下以添加文章类别字段至列表页为例,展示该功能。注意,自定义列表列和自定义字段是不同概念《 关于自定义字段,详见:wordpress-利用自定义字段实现网页静态数据后台编辑 》。
◆ 注册自定义列
manage_posts_columns,这是一个过滤器钩子,可以对其返回数据进行拦截,并修改其内容。manage_posts_columns 钩子会在 WordPress 渲染文章列表管理页面的列标题时被触发。它接收一个包含当前列信息的数组作为参数,这个数组的键是列的标识符,值是列的显示标题。开发者可以在回调函数中对这个数组进行修改,然后返回修改后的数组,WordPress 会根据返回的数组来显示列标题。注意:manage_posts_columns会对所有类型文章生效,我只想对特定文章类型生效,则需要使用 manage_{$post_type}_posts_columns 钩子,其中 {$post_type} 是具体的自定义文章类型名称。本人的文章类型为【fanhua_category】,所以该过滤器应为manage_fanhua_history_posts_columns。
// 注册自定义列
function add_custom_columns( $columns ) {
// 在原有的列数组中添加一个新的列,键为 custom_column,值为显示的标题
$columns['fanhua_category_column'] = '分类';
return $columns;
}
add_filter( 'manage_fanhua_history_posts_columns',[ $this, 'add_custom_columns']);
调试$columns值如下:
{
"cb": "<input type=\"checkbox\" />",
"title": "标题",
"date": "日期"
}
◆ 给自定义列赋值并显示
添加自定义列后,列标题虽然显示出来了,但列中并没有具体内容。若要为自定义列填充内容《具体参见: wordpress-文章列表页渲染过程 》,需要使用 manage_posts_custom_column(同样针对所有文章类型)或 manage_{$post_type}_posts_custom_column(针对自定义文章类型)动作钩子,给先前所注册的列赋值。
// 给自定义列赋值
function display_custom_column_content( $column, $post_id ) {
if ( $column === 'fanhua_category_column' ) {
$terms = get_the_terms($post_id, 'fanhua_category');
if ($terms && !is_wp_error($terms)) {
$term_names = array();
foreach ($terms as $term) {
$term_names[] = $term->name;
}
echo implode(', ', $term_names);
} else {
echo '无';
}
}
}
再次强调:$column参数不是所有要显示的列,而是当前正在处理的被指定的自定义列《具体参见: wordpress-文章列表页渲染过程 》。
其中get_the_terms($post_id, ‘fanhua_category’),其中这个函数是对查询terms(术语)sql进行封装。即根据文章id、taxonomy(类别)获取具体的术语。