如果你開始使用manage_{post_type}_posts_columns這個鉤子了,說明你的WordPress水平已經(jīng)提升到一個不錯的階段,不在滿足于主題的開發(fā),而是開始研究后臺的開發(fā)了。
這個鉤子的主要作用是給我們的網(wǎng)站的文章添加一些新的字段名稱,默認的字段名稱如下圖所示,包括標題、作者、分類目錄等等,如果我們想要添加一個新的字段,就需要使用這個鉤子了
和其他鉤子的使用一樣,我就直接展示代碼了,如果是針對我們的文章進行字段的添加,鉤子的名字就寫用manage_posts_columns和manage_posts_custom_column就行。
如果需要重新排列字段的順序,直接創(chuàng)建一個包含新順序的數(shù)組即可,處理代碼不變
在functions.php添加下面代碼
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 type添加字段功能就需要使用這兩種鉤子manage_{post_type}_posts_columns和?manage_{post_type}_posts_custom_column
只需要把{post_type}換成你的Post type的名稱,比如我們注冊一個product的形式,則代碼如下
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="/uploads/img/<?php echo $array_image_url[0];?>">
<?php }else{
echo 'None';
}
break;
default:
break;
}
}
效果展示
add_action()參數(shù)中的10和2分別表示該函數(shù)執(zhí)行的優(yōu)先級是10(默認值,值越小優(yōu)先級越高),該函數(shù)接受2個參數(shù)。