管理画面の投稿一覧にカスタムフィールドの絞り込み検索を追加する
WordPressの管理画面にある投稿一覧では、日付とカテゴリーによるプルダウン(選択)式の絞り込み検索が用意されています。
投稿にカスタムフィールドを追加していて、カスタムフィールドでも絞り込み検索ができるようにしたい場合はfunctions.phpに下記のように記載します。(色のカスタムフィールド(color)に対する絞りこみ項目として、「すべての色」(初期値)、「赤」(red)、「黄色」(yellow)、「青」(blue)を選択肢として持つプルダウンを用意する例です)
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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
/** * 管理画面の投稿一覧にカスタムフィールドの絞り込み選択機能を追加します。 */ function restrict_manage_posts_custom_field() { // 投稿タイプが投稿の場合 (カスタム投稿タイプのみに適用したい場合は 'post' をカスタム投稿タイプの内部名に変更してください) if ( 'post' == get_current_screen()->post_type ) { // カスタムフィールドのキー(名称例) $meta_key = 'color'; // カスタムフィールドの値の一覧(例。「=>」の左側が保存されている値、右側がプルダウンに表示する名称です。) $items = array( '' => 'すべての色', 'red' => '赤', 'yellow' => '黄色', 'blue' => '青' ); // Advanced Custom Fields を導入してフィールドタイプをセレクトボックスなど // 選択肢のあるタイプにしている場合は下記のような形でも可です。 // $field = get_field_object($meta_key); // $items = array_merge( array( '' => 'すべての色' ), $field['choices'] ); // 選択されている値 // ( query_vars フィルタでカスタムフィールドのキーを登録している場合は get_query_var( $meta_key ) でも可です ) $selected_value = filter_input( INPUT_GET, $meta_key ); // プルダウンのHTML $output = ''; $output .= '<select name="' . esc_attr($meta_key) . '">'; foreach ( $items as $value => $text ) { $selected = selected( $selected_value, $value, false ); $output .= '<option value="' . esc_attr($value) . '"' . $selected . '>' . esc_html($text) . '</option>'; } $output .= '</select>'; echo $output; } } add_action( 'restrict_manage_posts', 'restrict_manage_posts_custom_field' ); /** * 管理画面の投稿一覧に追加したカスタムフィールドの絞り込みの選択値を反映させます。 * (絞り込みが必要なカスタムフィールドが1つの場合)] * @param WP_Query $query クエリオブジェクト */ function pre_get_posts_admin_custom_field( $query ) { // 管理画面 / 投稿タイプが投稿 / メインクエリ、のすべての条件を満たす場合 // (カスタム投稿タイプのみに適用したい場合は 'post' をカスタム投稿タイプの内部名に変更してください) if ( is_admin() && 'post' == get_current_screen()->post_type && $query->is_main_query() ) { // カスタムフィールドのキー(名称例) $meta_key = 'color'; // 選択されている値 // ( query_vars フィルタでカスタムフィールドのキーを登録している場合は get_query_var( $meta_key ) でも可です ) $meta_value = filter_input( INPUT_GET, $meta_key ); // クエリの検索条件に追加 // (すでに他のカスタムフィールドの条件がセットされている場合は条件を引き継いで新しい条件を追加する形になります) if ( strlen( $meta_value ) ) { $meta_query = $query->get( 'meta_query' ); if ( ! is_array( $meta_query ) ) $meta_query = array(); $meta_query[] = array( 'key' => $meta_key, 'value' => $meta_value ); $query->set( 'meta_query', $meta_query ); } } } add_action( 'pre_get_posts', 'pre_get_posts_admin_custom_field' ); |