問題 × 解決策

WordPressの管理画面のカスタム投稿の一覧でカスタムフィールドの項目を追加する

問題

Wordpressの管理画面のカスタム投稿の一覧でカスタムフィールドの項目を追加するには?

解決策

functions.phpにて、以下を記述する。

  • 「manage_posts_columns」をフックしてカスタムフィールド用の項目を追加する。
  • 「manage_カスタム投稿名_posts_custom_column」をフックし、カスタムフィールドの項目での値の表示の処理を行う。

 

カスタムフィールドの項目を追加

WordPressの管理画面のカスタム投稿の一覧でカスタムフィールドの項目を追加する方法をご紹介します。

「manage_posts_columns」をフックしてカスタムフィールド用の項目を追加する。

functions.phpにて、「manage_posts_columns」をフックして、「$columns[‘カスタムフィールド名’] = ‘カスタムフィールドのラベル’;」を記述し、returnで返します。

functions.php

function add_posts_columns( $columns ) {
  $columns['カスタムフィールド名'] = 'カスタムフィールドのラベル';
  return $columns;
}
add_filter( 'manage_posts_columns', 'add_posts_columns' );

「manage_カスタム投稿名_posts_custom_column」をフックし、カスタムフィールドの項目での値の表示の処理を行う。

functions.phpにて、「manage_カスタム投稿名_posts_custom_column」をフックして、カスタムフィールドの項目の時に値を取得して表記させます。

functions.php

function カスタム投稿名_columns_content($column_name, $post_id) {
  if( $column_name == 'カスタムフィールド名' ) {
    $metas = get_post_meta($post_id);
    $stitle = $metas['カスタムフィールド名'][0];
  }
 
  if ( isset($stitle) && $stitle ) {
    echo esc_attr($stitle);
  }
}
add_action( 'manage_カスタム投稿名_posts_custom_column', 'カスタム投稿名_columns_content', 10, 2 );

参照

以下のサイトが、より詳しく解説してくれています。

【WordPress:管理画面の一覧ページにカスタムフィールドの値を表示する項目を追加する方法 | NxWorld】
https://www.nxworld.net/wordpress/wp-add-posts-columns-custom-fields.html

コメント

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

20 − eleven =

「問題 × 解決策」
月別アーカイブ一覧

「問題 × 解決策」
月別アーカイブ一覧