WordPress管理画面のカスタム投稿一覧でカテゴリを表示する

※当サイトでは広告を掲載しています

管理画面上でカスタム投稿の一覧を表示すると、カテゴリが表示されていないので非常に不便。なので、カテゴリ列を追加して表示できるようにします。

今回、カスタム投稿を3つ設定していると仮定し、手順をメモメモ。

functions.phpの編集

まず、functions.phpで、カスタム投稿タイプとカスタムタクソノミー(カテゴリ)を以下のように追加しているとします。分かりやすいように、投稿タイプのスラッグを「posttype」、タクソノミー(カテゴリ)のスラッグを「taxonomy」から始まる連番にしています。

register_post_type( 'posttype1', array( ~略~ ) );
register_taxonomy( 'taxonomy1', 'posttype1', array( ~略~ ) );

register_post_type( 'posttype2', array( ~略~ ) );
register_taxonomy( 'taxonomy2', 'posttype2', array( ~略~ ) );

register_post_type( 'posttype3', array( ~略~ ) );
register_taxonomy( 'taxonomy3', 'posttype3', array( ~略~ ) );

続いて、以下の記述を追加します。場所は特に指定はありませんが、とりあえずファイルの最後に追加しておけば問題ないかと。

function add_custom_column( $column ){
    global $post_type;
    if( $post_type === 'posttype1' ){
        $column['taxonomy1'] = 'カテゴリ列のタイトル';
    } else if( $post_type === 'posttype2' ){
        $column['taxonomy2'] = 'カテゴリ列のタイトル';
    } else if( $post_type === 'posttype3' ){
        $column['taxonomy3'] = 'カテゴリ列のタイトル';
    }
    return $column;
}
add_filter( 'manage_posts_columns', 'add_custom_column' );

function add_custom_column_id( $column_name, $id ){
    if( $column_name === 'taxonomy1' ) {
        echo get_the_term_list( $id, 'taxonomy1', '', ', ' );
    } else if( $column_name === 'taxonomy2' ) {
        echo get_the_term_list( $id, 'taxonomy2', '', ', ' );
    } else if( $column_name === 'taxonomy3' ) {
        echo get_the_term_list( $id, 'taxonomy3', '', ', ' );
    }
}
add_action( 'manage_posttype1_posts_custom_column', 'add_custom_column_id', 10, 2 );
add_action( 'manage_posttype2_posts_custom_column', 'add_custom_column_id', 10, 2 );
add_action( 'manage_posttype3_posts_custom_column', 'add_custom_column_id', 10, 2 );

これで、管理画面の3つのカスタム投稿一覧に、それぞれカテゴリ列が追加されます。カテゴリが表示されるだけで、だいぶ使いやすくなりますね。

ついでに絞り込み機能も追加

せっかくカテゴリが表示できたんだから、絞り込み機能も追加しておきましょう。これがあれば更に便利に!
function add_posts_taxonomy_filter() {
    global $post_type;
    $taxonomy = '';
    if( $post_type === 'posttype1' ){
        $taxonomy = 'taxonomy1';
    } else if( $post_type === 'posttype2' ){
        $taxonomy = 'taxonomy2';
    } else if( $post_type === 'posttype3' ){
        $taxonomy = 'taxonomy3';
    }

    if( !empty( $taxonomy ) ){
        print "<select name=\"{$taxonomy}\">\n";
        print "<option value=\"\">カテゴリ指定なし</option>\n";
        $terms = get_terms( $taxonomy );
        foreach( $terms as $term ){
            print "<option value=\"{$term->slug}\">{$term->name}</option>\n";
        }
        print "</select>\n";
    }
}
add_action( 'restrict_manage_posts', 'add_posts_taxonomy_filter' );

ここまで追加しておけば、だいぶ管理が楽になるのではないでしょうか。

あ、言い忘れました。何かあってからでは遅いので、作業前にfunctions.phpのバックアップを取っておくことをお忘れなく!

初稿:2021年2月16日

コメント

タイトルとURLをコピーしました