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": "日期"
}

◆ 给自定义列赋值并显示

// 给自定义列赋值
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 '无';
        }
    }
}

其中get_the_terms($post_id, ‘fanhua_category’),其中这个函数是对查询terms(术语)sql进行封装。即根据文章id、taxonomy(类别)获取具体的术语。