DEV Community

kumamon
kumamon

Posted on

【WordPress】サイト内検索実装までの流れ

検索窓の挿入

<?php get_search_form(); ?>

検索窓 searchform.php

php

<form role="search" method="get" class="search-form" action="<?php echo home_url( '/' ); ?>">
<label>
<input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'サイト内検索', 'placeholder' ) ?>" value="<?php echo get_search_query() ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label' ) ?>" />
</label>
</form>

style

.search-field{
background:#e8f3ff;
text-align:center;
border:none;
box-shadow:2px 2px 2px #e0e0e0;
height:40px;
padding:0 0 0 10px;

}

.search-form{
margin:10px 0;
text-align:center;
}

/*****サイドバー使うなら***/
.formside{
width:165px;
margin-top: 20px;
}

サイト内検索結果ページ search.php

php

<?php get_search_form(); ?>
<div class="search-result">


<?php
    global $wp_query;
    $total_results = $wp_query->found_posts;
    $search_query = get_search_query();
?>

<h1><?php echo $search_query; ?>の検索結果<span>(<?php echo $total_results; ?>件)</span></h1>

<?php
if( $total_results >0 ):
if(have_posts()):
while(have_posts()): the_post();
?>

<a href="<?php the_permalink(); ?>">
<div class="search-result-link">

<h2><?php the_title(); ?></h2>
<?php the_excerpt(); ?> 
    </div></a>

<?php endwhile; endif; else: ?>


<?php echo $search_query; ?> に一致するページは見つかりませんでした。

<?php endif; ?>
<nav class="pagination-area">
<?php
the_posts_pagination( array (
'prev_text' => 'PREV',
'next_text' => 'NEXT',
'mid_size'  => 2
) );
?>
</nav>              

</div>
<?php get_search_form(); ?>

style

 .search-result{
margin:36px 16px;

}
.search-result p{
margin:12px 0 18px 0; 

}

.search-result h1{
margin-bottom:16px;
}

.search-result a{

text-decoration:none;
color:#6b6b6b;

}

.search-result-link{
border:solid 2px #ff9b64;
border-radius:4px;
margin:12px 0 ;
padding:16px;
box-shadow:2px 2px 2px #d0d0d0 ;
}   
.nav-links {
font-size:20px;
text-align:center;
}

除外ページの設定

function search_pre_get_posts( $query ) {
if ( $query->is_search && !is_admin() ){
$query->set( 'post__not_in', array(★★,★★) );
}
return $query;
}
add_action( 'pre_get_posts', 'search_pre_get_posts' );

ページネーションのstyle
https://dev.to/kumamon/wordpress-style-3e8h

Top comments (0)