検索結果の並び替え
WordPressの検索結果で検索文字をキーに並び替える方法
「search.php」に下記を記述する
<div class="container">
<div class="posts">
<h3>「<?php echo get_search_query() ?>」を含む項目</h3>
<ul>
<?php
// 検索文字を取得
$search_string = get_search_query();
//検索文字をキーにタイトル順で現在のカテゴリを格納
$args = array(
's' => $search_string,
'orderby' => 'title',
'order' => 'ASC'
);
$query = new WP_Query($args);
if ($query->have_posts()):
while ($query->have_posts()):
$query->the_post();
?>
<li class="list"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
<?php
endwhile;
else:
?>
<p>該当無し</p>
<?php
endif;
?>
</div>
</ul>
</div>
「get_search_query()」で検索文字を取得し、変数「$search_string」に格納
「’s’ => $search_string」で「$args」に検索文字をセット
「’orderby’ => ‘title’」で「’order’ => ‘ASC’」でタイトルを昇順にセット
※WP_Query($args) ⇒ 関数リファレンス/WP_Query