NB: Make sure you do a back up of your theme, files and database before attempting the tutorials
Last modified : Sep 16 2022
Estimated reading time : 1 minute, 27 seconds - 118 words
Share the post "WordPress Search Function"
Sometimes, it is possible that you experience query issues occur especially with Custom Post Type. Here’s a solution to address this issue.
Here’s a function that do an advanced search to optimize your users’ searches on your website. First of all, make sure that the searchform.php is triggered properly.
<form id="searchform" role="search" action="<?php echo home_url( '/' ); ?>" method="get"><input id="s" name="s" type="text" value="<?php the_search_query(); ?>" /> <input id="searchsubmit" type="submit" value="" /></form>
Afterwards you need to add a function filter to your functions.php file.
///////////////////////////////////////
// Requete de recherche mots clés tous post
///////////////////////////////////////
function searchfilter($query) {
if ($query->is_search && !is_admin() ) {
$query->set('post_type',array('post','recettes'));
}
return $query;
}
add_filter('pre_get_posts','searchfilter');You’ll notice that with this filter, we do a query on general posts but also a Custom Post Type. Simply replace the Custom Post Type by yours.
Let’s image that we have a second Custom Post Type called portfolio, so how can we add it after the first one?
///////////////////////////////////////
// Requete de recherche mots clés tous post
///////////////////////////////////////
function searchfilter($query) {
if ($query->is_search && !is_admin() ) {
$query->set('post_type',array('post','recettes','portfolio'));
}
return $query;
}
add_filter('pre_get_posts','searchfilter');Your search.php will display the results.