WordPressで検索フォームを設置する方法

ここでは、WordPressで検索フォームを設置する方法について説明していきます。

「searchform.php」ファイルの作成

「searchform.php」ファイルに検索フォームを入力します。
この時、以下のルールを守る必要があります。

  • actionをホームへのURLにする。
  • methodを「get」にする。
  • nameを「s」にする。

構文

<form action="ホームへのURL" method="get">
  <input type="text" name="s" value="<?php the_search_query(); ?>" placeholder="キーワードを入力">
</form>

使用例

<form action="<?php echo home_url('/'); ?>" method="get" class="header__search header-search">
  <input type="text" name="s" value="<?php the_search_query(); ?>" placeholder="キーワードを入力">
  <!-- <i class="fas fa-search"></i> -->
</form>

「search.php」ファイルの作成

「search.php」ファイルを作成して検索結果を表示させます。

<?php get_header(); ?>

<main class="main">
  <div class="main__inner">
    <h2 class="main__page-title">サイト内検索<span>SEARCH</span></h2>
    <h3 class="main__search-result">「<?php the_search_query(); ?>」の検索結果</h3>
    <?php
    if (have_posts()) :
      while (have_posts()) : the_post();
        get_template_part('template-parts/card');
      endwhile;
    endif;
    ?>
  </div>
  <!-- /.main__inner -->
</main>

<?php get_footer(); ?>

※get_template_part(‘template-parts/card’);では、「card.php」ファイルを読み込んでいます。

card.php

<a href="<?php the_permalink(); ?>" class="cards__item card">
  <figure class="card__img-wrapper">
    <?php if (has_post_thumbnail()) : ?>
      <?php the_post_thumbnail(); ?>
    <?php else : ?>
      <?php echo wp_get_attachment_image(画像ID); ?>
    <?php endif; ?>
  </figure>
  <div class="card__body">
    <h3 class="card__title">
      <?php the_title(); ?>
    </h3>
    <p class="card__text">
      <?php the_excerpt(); ?>
    </p>
  </div>
  <!-- /.card__body -->
</a>

get_search_form()

検索フォームを設置したい場所にget_search_form()を記述します。

<header class="header">
  <div class="header__inner">
    <?php wp_nav_menu(array(
      "container" => false,
      "menu_class" => "header__menu header-menu",
      "theme_location" => "header-nav",
    )); ?>
    <?php get_search_form(); ?>
  </div>
  <!-- /.header__inner -->
</header>

検索フォーム

検索結果

まとめ

このように、「searchform.php」で検索フォームを、「search.php」で検索結果を、「get_search_form()」を検索フォームを設置する場所に記述することで、検索フォームを設置することができます。