blog
copyright ©
creamu Inc. All Rights Reserved.
art direction & design: Kunitaka Kawashimo
code, interaction & photography: creamu Inc.
category: Web

WordPressのカスタム投稿タイプにカテゴリーとサムネイルを表示する方法

Pocket

WordPressの投稿や固定ページ一覧ページにアイキャッチ画像を表示し、カスタム投稿タイプにカテゴリーとサムネイルを表示する方法です。

以下のコードをfunctions.phpに追記します。

//投稿一覧ページや固定ページ一覧ページにアイキャッチ画像用の列を追加する
add_filter( ‘manage_posts_columns’, ‘add_custom_columns_for_thumb’); //投稿 & カスタム投稿
add_filter( ‘manage_pages_columns’, ‘add_custom_columns_for_thumb’ ); //固定ページ
if ( ! function_exists( ‘add_custom_columns_for_thumb’ ) ) {
function add_custom_columns_for_thumb( $columns ) {
$columns[‘thumbnail’] = ‘アイキャッチ画像’; //アイキャッチ画像用カラムのキー名と表示名を任意で設定
return $columns;
}
}
add_action( ‘manage_posts_custom_column’, ‘output_custom_columns_for_thumb’, 10, 2 ); //投稿 & カスタム投稿(階層構造が無効)
add_action( ‘manage_pages_custom_column’, ‘output_custom_columns_for_thumb’, 10, 2 ); //固定ページ & カスタム投稿(階層構造が有効)
if ( ! function_exists( ‘output_custom_columns_for_thumb’ ) ) {
function output_custom_columns_for_thumb( $column_name, $post_id ) {
if ( ‘thumbnail’ === $column_name ) {
//上で決めたキー名’thumbnail’があれば
$thumb_img = get_the_post_thumbnail( $post_id, array(50,50), ‘thumbnail’ );
echo $thumb_img ?: ‘-‘;
}
}
}

//管理画面のカスタム投稿タイプ(投稿タイプ:blog/タクソノミー:tax_blog(変更がある場合は変更する))に、サムネイルとカテゴリーを追加する
function add_custom_column( $defaults ) {
$defaults[‘tax_blog’] = ‘カテゴリー’;
$defaults[‘thumbnail’] = ‘サムネイル’;
return $defaults;
}
add_filter(‘manage_blog_posts_columns’, ‘add_custom_column’);

function add_custom_column_id($column_name, $id) {
if( $column_name == ‘tax_blog’ ) {
echo get_the_term_list($id, ‘tax_blog’, ”, ‘, ‘);
}
}
add_action(‘manage_blog_posts_custom_column’, ‘add_custom_column_id’, 10, 2);

function sort_custom_columns( $columns ) {
$columns = array(
‘cb’ => ‘<input type=”checkbox” />’,
‘title’ => ‘タイトル’,
‘tax_blog’ => ‘カテゴリー’,
‘tags’ => ‘タグ’,
‘date’ => ‘日付’,
‘thumbnail’ => ‘サムネイル’
);
return $columns;
}
add_filter( ‘manage_blog_posts_columns’, ‘sort_custom_columns’ );