LoginSignup
0
0

More than 3 years have passed since last update.

Wordpress サイトの検索結果を「カスタム投稿のみ」「カスタムフィールドで並び替え」にする

Posted at

Wordpress サイトの検索結果を「カスタム投稿のみ」「カスタムフィールドで並び替え」にする

Wordpress サイトのカスタマイズでサイト内検索の結果を「カスタム投稿のみ」「カスタムフィールドで並び替え」られたものにしたいと要望を受けた際の対応のメモ。

結果

                         
functions.php で pre_get_postsposts_search をフックに処理かませた。

function post_type_filter_and_sort( $query ) {
    if ( !is_admin() && $query->is_main_query() && $query->is_search() ) {
        $query->set( 'post_type', 'カスタム投稿タイプ名' );
        $query->set( 'orderby', 'meta_value' );
        $query->set( 'meta_key', 'ソートしたいフィールド名' );
        $query->set( 'order', 'ASC' );
        $query->set( 'posts_per_page', $posts_per_page );
    }
    return $query;
}
add_filter( 'pre_get_posts', 'post_type_filter_and_sort' );

function title_filter( $search, $query ) {
    global $wpdb;
    if (
        !is_admin() &&
        $query->is_main_query() &&
        $query->is_search() &&
        isset( $query->query_vars[ 'search_terms' ] )
    ) {
        $terms = $query->query_vars[ 'search_terms' ];
        $search = "AND post_type = 'カスタム投稿タイプ名'";
        $sql_operator = "AND";
        foreach ( $terms as $term ) {
            if ( !empty($term) ) {
                $search_term = '%' . esc_sql( $term ) . '%';
                $search .= " {$sql_operator} ({$wpdb->posts}.post_title LIKE '{$search_term}')";
                $sql_operator = "OR";
            }
        }
    }
    return $search;
}
add_filter( 'posts_search', 'title_filter', $posts_per_page, 2 );

pre_get_posts にフックしてタイトルのみを検索対象に含める処理ができず、
ORDER BY~ 追記するなど試したがなど試したが、
posts_search にフックして並び替えをすることもできなかった。

結果合わせ技にして実装。

参考

pre_get_posts | Hook | WordPress Developer Resources
posts_search | Hook | WordPress Developer Resources

環境

PHP: 7.1.32
mysql: 5.6.23
WordPress: 5.4.2

プラグイン

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0