自定义字段manage_{post_type}_posts_columns栏目文章列表添加钩子

文章添加一些新的字段名称,默认的字段名称如下图所示,包括标题、作者、分类目录等等,如果我们想要添加一个新的字段,就需要使用这个钩子了

和其他钩子的使用一样,我就直接展示代码了,如果是针对我们的文章进行字段的添加,钩子的名字就写用manage_posts_columns和manage_posts_custom_column就行。

如果需要重新排列字段的顺序,直接创建一个包含新顺序的数组即可,处理代码不变

cb – 复选框
title – 文章标题
author – 文章作者
categories – 文章的分类
tags – 文章的标签
comments – 文章的评论
date – 文章发布的日期
subtitle – 文章副标题
其他自定义
在functions.php添加下面代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
add_filter('manage_posts_columns', 'add_posts_columns');
function add_posts_columns() {
    $new_columns['cb'] = '<input type="checkbox" />';
    $new_columns['title'] = _x( 'Title', 'column name' );
    $new_columns['author'] = __('Author');
    $new_columns['categories'] = __('Categories');
    $new_columns['tags'] = __('Tags');
    $new_columns['id'] = __('ID');
    $new_columns['date'] = _x('Date', 'column name');
    return $new_columns;
}

add_action('manage_posts_custom_column', 'manage_posts_columns', 10, 2);
function manage_posts_columns($column_name, $id) {
    switch ($column_name) {
        case 'id':
            echo $id;
            break;
        default:
            break;
    }
}

post

如果我们想为自定义的post type添加字段功能就需要使用这两种钩子manage_{post_type}_posts_columns和 manage_{post_type}_posts_custom_column

只需要把{post_type}换成你的Post type的名称,比如我们注册一个product的形式,则代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
add_filter('manage_product_posts_columns', 'add_new_posts_columns');
function add_new_posts_columns() {
    $new_columns['cb'] = '<input type="checkbox" />';
    $new_columns['title'] = _x( 'Title', 'column name' );
    $new_columns['author'] = __('Author');
    $new_columns['categories'] = __('Categories');
    $new_columns['tags'] = __('Tags');
    $new_columns['id'] = __('ID');
    $new_columns['date'] = _x('Date', 'column name');
    $new_columns['thumbnail'] = _x('Thumbnail');
    return $new_columns;
}
add_action('manage_product_posts_custom_column', 'manage_product_posts_columns', 10, 2);
function manage_product_posts_columns($column_name, $id) {
    global $wpdb;
    global $post;
    switch ($column_name) {
        case 'id':
            echo $id;
            break;
        case 'categories':
            single_cat_title();
            break;
        case 'thumbnail':
            if (has_post_thumbnail()){
                $array_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array(75,60)); ?>
            <img width="75" height="60" src="<?php echo $array_image_url[0];?>">
            <?php }else{
                echo 'None';
            }
            break;
        default:
            break;
    }
}

product
转自:http://www.xuxiaoke.com/wphook/113.html

Leave a Reply

You must be logged in to post a comment.

RSS feed for comments on this post. TrackBack URL