WordPress Custom Query - Part 08 - Custom Search.mp4

C:\xampp\htdocs\wordpress\wp-content\themes\twentytwentyone\index.php

<?php get_header();?>
<div class="search-site">
  <form action="/wordpress" method="get">
    <input type="text" name="search_text">
    <label>Type:</label>
    <select name="type">
      <option value="any">Any</option>
      <option value="post">Posts</option>
      <option value="book">Book</option>           
    </select>
    <button type="submit">Search</button>
  </form>
</div>
<?php
if ($_GET['search_text'] && !empty($_GET['search_text'])) {
  $text = $_GET['search_text'];
}
if ($_GET['type'] && !empty($_GET['type'])) {
  $type = $_GET['type'];
}
?>
<div class="container">
  <h4>Searching for: <?php echo $text; ?></h4>
  <?php
  
	$args = array(
	  'post_type'      => $type,
	  'posts_per_page' => -1,
	  's'              => $text,
	  // 'exact' => true,
		// 'sentence' => true
	);
$query = new WP_Query($args);
while ($query->have_posts()): $query->the_post();
  ?>
	  <div class="post clearfix">
	    <h5><?php the_title();?></h5>
	    <strong>
	      <?php 
		      if (get_post_type() == 'post') {
		      	echo 'Post';
		      }
	      ?>
	      <?php 
	      	if (get_post_type() == 'book') {
	      		echo 'Book';
	      	}
	      ?>
	    </strong>
	  </div>
	  <?php endwhile;
wp_reset_query();?>
</div>
<?php get_footer();?>

Last updated