NB: Make sure you do a back up of your theme, files and database before attempting the tutorials

Easy

---- Last modified : Sep 10 2022

Estimated reading time : 2 minutes, 10 seconds - 186 words

In a previous tutorial, WordPress Search, we saw how to filter post types with WordPress’ search function. This tutorial will allow you to customize the search even more by creating a search post type for posts.

The first thing we need to do is create our Post Type form. The value needs to be the name of the Post Type. In our example, the post type is viavideos.

Search Post Type

<form class="search-form" role="search" action="<?php echo home_url( '/' ); ?>" method="get">
<label> 
<input class="search-field" title="<?php echo esc_attr_x( 'Rechercher :', 'label' ) ?>" name="s" type="search" value="<?php echo get_search_query() ?>" placeholder="<?php echo esc_attr_x( 'Rechercher …', 'placeholder' ) ?>" /> 
<input name="post_type" type="hidden" value="viavideos" /> 
</label> 
<input class="search-submit" type="submit" value="<?php echo esc_attr_x( 'Rechercher', 'submit button' ) ?>" />
</form>

Afterwards, we need to create the pre_get_post that will allow us to display the results of the Post type with the condition of search when you’re not an admin user. (Replace viavideos par votre Post Type).

function searchfilterquery($query) {
if ($query->is_search && !is_admin() ) {
	if(isset($_GET['post_type'])) {
		$type = $_GET['post_type'];
		if($type == 'viavideos') {
		   $query->set('post_type',array('viavideos'));
		}
	}
}
return $query;
}
add_filter('pre_get_posts','searchfilterquery');

We need to open the search.php file and add a new condition and add this new condition in your content’s loop in the search.php template.

Notice the results. We tell the search.php that if there’s a viavideos post type query, we need call the content-videos.php template. Or if it’s a post query, then the content-posts.php content Post template will be called. Otherwise, there will be no results.

<?php if(isset($_GET['post_type'])) { $type = $_GET['post_type']; if($type == 'viavideos') {?>
<?php get_template_part( 'content', 'videos' ); ?>

<?php } else { ?>
<?php get_template_part( 'content', 'posts' ); ?>
<?php } ?>

<?php } else { ?>
<?php _e( 'Pas de résultats' ); ?>
<?php } ?>

Simply try it out and test the results.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>