LoginSignup
10
5

More than 3 years have passed since last update.

[WordPress] 検索結果の並び順

Last updated at Posted at 2020-05-29

検索結果の並び順の根拠をたまに聞かれるので。
(追記)ロジックに関して追記しました。
https://twitter.com/tekapo/status/1266621537324371969

デフォルトは関連順

デフォルトの検索ウィンドウでサイト内検索した場合の記事の並び順。
3.7から関連順になってる。

検索の改善
より関連性のある検索結果となるよう改善

検索結果を表示するときの SQL

ORDER BY wp_posts.post_title LIKE '%検索してるテキスト%' DESC, wp_posts.post_date DESC

順序のロジックはこちら
https://core.trac.wordpress.org/changeset/25632

The ordering logic is as follows:
- Full sentence matches in post titles.
- All search terms in post titles.
- Any search terms in post titles.
- Full sentence matches in post content.
Each section and any remaining posts are then sorted by date.

投稿のタイトル>投稿本文の順で検索して行って同じ関連度なら日付でソート。

検索結果の並び順を変えたいとき

pre_get_posts ではなく posts_search_orderby フックで変更。
SQLのORDER BY句をそのまま記述する形で返す。
https://developer.wordpress.org/reference/hooks/posts_search_orderby/
例:日付順にする場合

/**
 * 検索結果は日付順にする
 */
add_filter( 'posts_search_orderby', 'my_posts_search_orderby', 10, 2 );
function my_posts_search_orderby( $search_orderby, $wp_query ) {
    return 'post_date desc';
}

現場からは以上です。

10
5
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
10
5