現在、WordPressサイトでカスタム投稿を使用した投稿に、カスタムフィールドを複数用意し検索しようと考えています。
いくつかサイトを参考にし、一つのカスタムフィールドから検索は可能になったのですが、2つ以上のカスタムフィールドをまたぐ検索をすると結果が0になります。
WordPressのバージョンは5.8、phpのバージョンは5.6.31、xamppで動かしています。
参考にしたサイトは
https://oku-log.com/blog/wp-search/
https://www.scitech.co.jp/include-customfields-search-target
で、自作のfunctions.phpに
// カスタム投稿用の検索結果テンプレートを用意 add_filter('template_include','custom_search_template'); function custom_search_template($template){ if ( is_search() ){ $post_types = get_query_var('post_type'); foreach ( (array) $post_types as $post_type ) $templates[] = "{$post_type}-search.php"; $templates[] = 'search.php'; $template = get_query_template('search',$templates); } return $template; }
と
// カスタムフィールドを検索対象にする function cf_search_join( $join ) { global $wpdb; if ( is_search() ) { $join .= ' LEFT JOIN ' . $wpdb->postmeta . ' ON ' . $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id '; } return $join; } add_filter( 'posts_join', 'cf_search_join' ); function cf_search_where( $where ) { global $wpdb; if ( is_search() ) { $where = preg_replace( "/(\s*" . $wpdb->posts . ".post_title\s+LIKE\s*(\'[^\']+\')\s*)/", "(" . $wpdb->posts . ".post_title LIKE $1) OR (" . $wpdb->postmeta . ".meta_value LIKE $1)", $where ); } return $where; } add_filter( 'posts_where', 'cf_search_where' ); function cf_search_distinct( $where ) { global $wpdb; if ( is_search() ) { return "DISTINCT"; } return $where; } add_filter( 'posts_distinct', 'cf_search_distinct' ); // 検索対象を『タイトルのみ』にする function __search_by_title_only( $search, & $wp_query ) { global $wpdb; if ( empty( $search ) ) return $search; // skip processing - no search term in query $q = $wp_query->query_vars; $n = !empty( $q[ 'exact' ] ) ? '' : '%'; $search = $searchand = ''; foreach ( ( array )$q[ 'search_terms' ] as $term ) { $term = esc_sql( like_escape( $term ) ); $search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')"; $searchand = ' AND '; } if ( !empty( $search ) ) { $search = " AND ({$search}) "; if ( !is_user_logged_in() ) $search .= " AND ($wpdb->posts.post_password = '') "; } return $search; } //add_filter( 'posts_search', '__search_by_title_only', 500, 2 );// (※2)
を記載しています。
例えば、「地域」と「価格」をカスタムフィールドで投稿し、
地域名(例えば「東京」)だけか価格(例えば「500円」)だけなら検索結果が正常に返りますが、
地域名と価格の両方で(「東京 500円」のような形)検索をしたいです。
カスタムフィールドは4つほど検索対象にしたいです。
また、カスタムフィールドはプラグインAdvanced Custom Field(ver. 5.9.9)を使用して、
カスタム投稿はcustom post type UI(ver. 1.9.2)を使用して作成しました。
詳しい方、ご教示いただけると助かります。
よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。