Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
Coupe WPB
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Comment limiter les résultats de recherche pour des types de publication spécifiques dans WordPress

Vous êtes-vous déjà demandé comment limiter vos recherches à des types de publication spécifiques ? Ce n’est pas très difficile. Nous vous avons déjà affiché comment désactiver la fonctionnalité de recherche en WordPress en modifiant le fichier functions.php. Maintenant, nous allons faire la même chose sauf pour filtrer nos résultats de recherche.

Ouvrez votre fichier functions.php et ajoutez les codes suivants :

function searchfilter($query) {

    if ($query->is_search && !is_admin() ) {
        $query->set('post_type',array('post','page'));
    }

return $query;
}

add_filter('pre_get_posts','searchfilter');

Notez la ligne qui dit

$query->set('post_type',array('post','page'));

Vous pouvez filtrer les résultats de la recherche en modifiant les valeurs du tableau. Pour l’instant, il est défini pour afficher les publications et les pages, mais vous pouvez le modifier pour afficher ce que vous voulez.

Divulgation : Notre contenu est soutenu par les lecteurs. Cela signifie que si vous cliquez sur certains de nos liens, nous pouvons gagner une commission. Consultez comment WPBeginner est financé, pourquoi cela compte et comment vous pouvez nous soutenir. Voici notre processus éditorial.

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

L'ultime WordPress Toolkit

Accédez GRATUITEMENT à notre boîte à outils - une collection de produits et de ressources liés à WordPress que tous les professionnels devraient avoir !

Reader Interactions

26 commentairesLaisser une réponse

  1. Ankit manandgar

    how can i get search results according to post title only?

  2. Anna

    Thanks for this code – it worked, although you last updated in 2013! My theme uses also an Instant Search and I would like to limit the results there aswell. How could I do that?

  3. Sparsh Goyal

    My present theme shows post with few starting lines for searched term/word. I want to customise it to show that paragraph having searched term/word in post excerpt. In other words, I want to show related text in post excerpt not starting paragraph in search results. Can anyone help me to do this….

  4. Azamat

    Hello,

    How can I limit search results for specific post types AND specific custom taxonomy terms?

  5. Steven

    I’ve got an easy function in my themes functions.php file, which should only filter the Posts by a search term… when I search something now, the HTTP 500 Error « The website cannot display the page » appears. Anyone got an Idea, whats wrong with my function?

    function searchFilter($query) {
    if ($query->is_search)
    {
    wp_reset_query();
    $args = array ( ‘s’ => $_GET[‘s’] );
    query_posts( $args );
    }
    }
    add_filter(‘pre_get_posts’, ‘searchFilter’);

  6. Greg

    This is restricting all search forms to the custom post type – including my sidebar searchform, which needs to return all results. This is working for me:

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

    • Jonathan Joosten

      Thanks for the assist, I improved your code so people can only search allowed post_types.

      function searchfilter($query)
      {
      if ($query->is_search && !is_admin() )
      {
      if(isset($_GET[‘post_type’])) {
      $types = (array) $_GET[‘post_type’];
      $allowed_types = get_post_types(array(‘public’ => true, ‘exclude_from_search’ => false));
      foreach($types as $type)
      {
      if( in_array( $type, $allowed_types ) ) { $filter_type[] = $type; }
      }
      if(count($filter_type))
      {
      $query->set(‘post_type’,$filter_type);
      }
      }
      }
      }
      add_filter(‘pre_get_posts’,’searchfilter’);

      • Dan Sz.

        How is this implemented? If I’m reading Greg’s comment, correctly we want a single form that is limited to a post type, while keeping default search intact for other areas of the site.

        I’m asking because a site i’m working on needs a searchable « Resource Library », which I’d like to build out with compromising the normal search functionality.

  7. Tadeu

    Hi, is it possible to limit search only to title, category and tags of posts?

  8. Sandeep

    Hi,

    I’m not able to restrict pages in search filter.
    I just need the search within the posts and not pages.

    $query->set(‘post_type’,array(‘post’));
    This displays pages too.

  9. Nick

    I used this code to restrict my search results to Pages, not Posts. It worked in that regard, however, it seems to only search the Page names as opposed to content. For instance, if a user searches « pricing », the Pricing page will be a result but if they search « price » or « cost » (both of which are words on the pricing page) nothing is found. Is there a snippet of code I’m missing?

  10. emre

    Hi,
    I have a question and I couldn’t get a solution since last month.
    I have lost of categories, pages and re-directions in my blog so my search box finds many unnecessary results when you try to search something. I want to customize my search.php for only categories part. In other words, we you search something, the results should be only from categories sections. So I will be get rid of redundant & duplicated results. My current codes are as below…Please help me :)

  11. sam

    How to limit by specific category? thanks

  12. Hasan Gad Allah

    Thank you , i was looking for that code (Y) :)

  13. Felix

    There’s one problem with your snippet:

    It limits the search results in the backend, you should wrap it with:


    if ( !is_admin() ) {
    // snippet
    }

  14. Alan Hughes

    So how would you apply this to a specific search bar? It doesn’t just apply the filter to every search bar on your site would it?

  15. scotte_sprott

    How can I limit search results to show just pages?

    • wpbeginner

      @scotte_sprott In the array, just keep page and remove posts.

Laisser une réponse

Merci d'avoir choisi de laisser un commentaire. Veuillez garder à l'esprit que tous les commentaires sont modérés selon notre politique de commentaires, et votre adresse e-mail ne sera PAS publiée. Veuillez NE PAS utiliser de mots-clés dans le champ du nom. Ayons une conversation personnelle et significative.