WordPressの検索フォームの検索範囲を変更する。
WordPressのフォーラムで検索フォームから検索すると投稿だけではなくページやカスタム投稿も表示されるのを
なんとかしたいという内容の質問がありました。
あれ?確かWordpressの検索は投稿のみしか検索しなかったと思ったんだけど違ったっけ?と思い調べてみると
元からなのか仕様が変わったのか確かにpost_typeの指定はありませんでした。
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 | // If a search pattern is specified, load the posts that match if ( ! empty ( $q [ 's' ]) ) { // added slashes screw with quote grouping when done early, so done later $q [ 's' ] = stripslashes ( $q [ 's' ]); if ( ! empty ( $q [ 'sentence' ]) ) { $q [ 'search_terms' ] = array ( $q [ 's' ]); } else { preg_match_all( '/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/' , $q [ 's' ], $matches ); $q [ 'search_terms' ] = array_map ( '_search_terms_tidy' , $matches [0]); } $n = ! empty ( $q [ 'exact' ]) ? '' : '%' ; $searchand = '' ; foreach ( ( array ) $q [ 'search_terms' ] as $term ) { $term = addslashes_gpc( $term ); $search .= "{$searchand}(($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}'))" ; $searchand = ' AND ' ; } $term = esc_sql( $q [ 's' ]); if ( empty ( $q [ 'sentence' ]) && count ( $q [ 'search_terms' ]) > 1 && $q [ 'search_terms' ][0] != $q [ 's' ] ) $search .= " OR ($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}')" ; if ( ! empty ( $search ) ) { $search = " AND ({$search}) " ; if ( !is_user_logged_in() ) $search .= " AND ($wpdb->posts.post_password = '') " ; } } // Allow plugins to contextually add/remove/modify the search section of the database query $search = apply_filters_ref_array( 'posts_search' , array ( $search , & $this ) ); |
検索はs=検索ワードなのでwp-includes/query.phpより関連しそうな場所をチェック。
post_typeの指定がないので投稿ページカスタム投稿問わず検索しているようです。都合良くposts_searchというフィルターがあったのでここにpost_typeを追加しましょう。
functions.phpに
1 2 3 4 5 | add_filter( 'posts_search' , 'post_only' ); function post_only( $search ){ $search .= " AND post_type = 'post'" ; return $search ; } |
これで投稿のみが検索に引っかかるはずです。
[…] This post was mentioned on Twitter by ゴーゴーウェブ池田, ゴーゴーウェブ池田. ゴーゴーウェブ池田 said: WordPressの検索フォームの検索範囲を変更する。 http://is.gd/Gy1Cip […]