WordPressで自作検索ページを実装する方法【簡単:プラグイン不要】

WordPressで自作検索ページを実装したい。
検索ボックスと検索結果を実装したい。
プラグインを使わず、実装したい。
本記事ではこのような疑問を解決、実装方法について解説します。
検索ボックスを実装する
<form class="form" action="<?= home_url(); ?>" method="get">
<input placeholder="検索" class="input-txt" type="text" name="s">
<button>検索</button>
</form>
検索ボックスを実装できるコード例です。
htmlでform要素を作成。
action属性にテンプレートタグのhome_url()。
method属性にgetを入れます。
テキストボックスをinput要素で作成。
name属性を入れ、値にsを入れます。
検索ボタンをbutton要素などで作成します。
以上で検索ボックスの完成です。
検索結果ページを実装する
<p class="ttl"><?php the_search_query(); ?>の検索結果</p>
<div class="list">
<?php if (have_posts() && get_search_query()) : ?>
<?php while (have_posts()) : the_post(); ?>
<!-- 検索結果の記事ループ -->
<a class="list-link" href="<?php the_permalink(); ?>">
<div class="list-thamnail">
<?php if (has_post_thumbnail()) : ?>
<img class="list-img" src="<?php the_post_thumbnail_url('full'); ?>">
<?php else : ?>
<img src="<?php the_post_thumbnail_url('full'); ?>">
<?php endif; ?>
</div>
<div class="list-cate">
<?php if ($categories) : ?>
<?php foreach ($categories as $value) : $categories_id = $value->term_taxonomy_id; ?>
<span>
<?php echo $value->name; ?>
</span>
<?php endforeach; ?>
<?php endif; ?>
</div>
<p class="list-title">
<?php the_title(); ?>
</p>
<div class="list-date">
<span class="entry">
<?php the_time('Y/m/d'); ?>
</span>
<?php if (get_the_time('Y/m/d') != get_the_modified_date('Y/m/d')) : ?>
<span class="update">
(更新日:<?php the_modified_date('Y/m/d') ?>)
</span>
<?php endif; ?>
</div>
</a>
<?php endwhile; ?>
<div class="list list-kara"></div>
<?php else : ?>
<p>検索結果が見つかりませんでした。</p>
<?php endif; ?>
</div>
<!-- ページネーション -->
<?php
$big = 999999999;
echo "<div id='pagenation'>";
echo paginate_links(array(
'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
'current' => max(1, get_query_var('paged')),
'prev_next' => true,
'prev_text' => '<',
'next_text' => '>',
));
echo "</div>";
?>
検索結果ページのコード例です。
search.phpをテーマフォルダ内に作成、上記コードをコピーします。
the_search_query()
で検索されたテキストを出力します。
while文内で検索結果に出したい投稿記事一覧の要素を入れます。
最後にpaginate_links()
を使ってページネーションを入れれば完成です。
以上の流れで自作検索ページを実装できます。
簡単ですね。
まとめ
デフォルトの投稿を検索したい場合は本記事の方法だけで簡単に検索ページを自作できるのでおすすめです。
以上で解説を終わります。
目次