Learning site for website creation

p06-6:カスタム投稿を検索結果に反映させる「Custom Post Type UI」

公開日:2018年11月17日 更新日:2018年11月21日

「Custom Post Type UI」を使って作成したカスタム投稿を検索結果に表示させます。

「Custom Post Type UI」の設定で検索結果にカスタム投稿が表示されるはずですが、現在表示結果に反映されていません。

検索結果表示用テンプレート「search.php」を確認します。

search.php

変更前

検索結果から固定ページを除外するためメインループのデータを再取得しています。

その際、条件として「’post_type’ => ‘post’,」と指定しており、投稿のみ検索結果に表示しています。

<?php get_header(); ?>

<?php
// 検索値取得
$s = $_GET['s'] ? $_GET['s'] : NULL;

// メインループ条件変更
$paged = max(1, get_query_var('paged'));
$args = array (
  'paged' => $paged,
  'post_status' => 'publish',
  'post_type' => 'post',
  's' => $s,
);
query_posts( $args );

// 検索結果の記事数
$found_posts = $wp_query->found_posts;
?>

  <div class="content">
    <div class="main">

<?php // 検索タイトル表示 ?>

      <div class="main-loop">
        <div class="inner">
        <h1><?php the_search_query();?> の検索結果:<?php echo $found_posts;?>件</h1>
<?php /***** メインループ開始 *****/ ?>
<?php if (have_posts()) :?>
<?php while (have_posts()) : the_post(); ?>
<?php $id = get_the_ID(); ?>
<?php // テンプレートパーツ読み込み:一覧 ?>
<?php get_template_part('content'); ?>
<?php endwhile; ?>
<?php else: ?>
<?php // テンプレートパーツ読み込み:記事なし ?>
<?php get_template_part('content','none'); ?>
<?php endif; ?>
<?php /***** メインループ終了 *****/ ?>

<?php // ページネーション ?>
<?php if (pagination()) : ?>
    <div class="pagination"><?php echo pagination(); ?></div>
<?php endif; ?>

        </div><!-- /.inner -->
      </div><!-- /.main-loop -->
    </div><!-- /.main -->
    <?php get_sidebar(); ?>
  </div><!-- /.content -->

<?php
get_footer();

変更後

作成したカスタム投稿も反映されるよう条件「’post_type’ => ‘post’,」を「’post_type’ => array(‘post’, ‘post_news’),」に変更します。

<?php get_header(); ?>

<?php
// 検索値取得
$s = $_GET['s'] ? $_GET['s'] : NULL;

// メインループ条件変更
$paged = max(1, get_query_var('paged'));
$args = array (
  'paged' => $paged,
  'post_status' => 'publish',
  'post_type' => array('post', 'post_news'),
  's' => $s,
);
query_posts( $args );

// 検索結果の記事数
$found_posts = $wp_query->found_posts;
?>

  <div class="content">
    <div class="main">

<?php // 検索タイトル表示 ?>

      <div class="main-loop">
        <div class="inner">
        <h1><?php the_search_query();?> の検索結果:<?php echo $found_posts;?>件</h1>
<?php /***** メインループ開始 *****/ ?>
<?php if (have_posts()) :?>
<?php while (have_posts()) : the_post(); ?>
<?php $id = get_the_ID(); ?>
<?php // テンプレートパーツ読み込み:一覧 ?>
<?php get_template_part('content'); ?>
<?php endwhile; ?>
<?php else: ?>
<?php // テンプレートパーツ読み込み:記事なし ?>
<?php get_template_part('content','none'); ?>
<?php endif; ?>
<?php /***** メインループ終了 *****/ ?>

<?php // ページネーション ?>
<?php if (pagination()) : ?>
    <div class="pagination"><?php echo pagination(); ?></div>
<?php endif; ?>

        </div><!-- /.inner -->
      </div><!-- /.main-loop -->
    </div><!-- /.main -->
    <?php get_sidebar(); ?>
  </div><!-- /.content -->

<?php
get_footer();

変更後、検索結果を表示するとカスタム投稿も反映しています。

同じタグのコンテンツ