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

Afficher le terme de recherche et le nombre de résultats dans WordPress

Note éditoriale : Nous percevons une commission sur les liens des partenaires sur WPBeginner. Les commissions n'affectent pas les opinions ou les évaluations de nos rédacteurs. En savoir plus sur Processus éditorial.

Dans ce tutoriel, nous allons vous expliquer comment vous pouvez ajouter un module simple sur votre page de recherche qui affichera le terme recherché et le nombre de résultats. Cette fonctionnalité a été demandée par l’un de nos utilisateurs/utilisatrices par e-mail. Si vous souhaitez que nous traitions un sujet, n’hésitez pas à nous faire part de vos suggestions.

Displaying search term and result count in WordPress search

Ouvrez votre fichier search.php dans votre thème et ajoutez le code suivant :

<h2 class="pagetitle">Search Result for <?php /* Search Count */ $allsearch = new WP_Query("s=$s&showposts=-1"); $key = wp_specialchars($s, 1); $count = $allsearch->post_count; _e(''); _e('<span class="search-terms">'); echo $key; _e('</span>'); _e(' &mdash; '); echo $count . ' '; _e('articles'); wp_reset_query(); ?></h2>

Le code ci-dessus affichera quelque chose comme ceci :

Résultat de la recherche pour twitter – 15 articles

Vous pouvez également mettre en évidence le terme recherché en ajoutant la classe CSS .search-terms à la feuille de style de votre thème. Voici une feuille de style CSS simple pour Premiers pas :

.search-terms {
background-color:yellow;
color:blue;
}

Ce n’est là qu’une des nombreuses possibilités de personnalisation de votre page de recherche. Vous pouvez également mettre en évidence les termes recherchés dans les résultats, et même ajouter une fonctionnalité de recherche par catégorie à votre recherche WordPress.

Source : Michael Martin

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

16 commentairesLaisser une réponse

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Aniruddh says

    Can I use this code in the sidebar.php file? As I need to show the search term and result count in the sidebar. Please help.

  3. Marco says

    thanks a lot for this snippet! :)

    according to the wp codex the function wp_specialchars is deprecated. it says that you should use esc_html instead.

    regards,
    marco

  4. Henry says

    echo $wp_query->found_posts;
     
    Adding this to the top of your search page will display the number of posts found for a particular search.
     
    echo get_search_query();
     
    This will display the search term (entered in to the search box by your site visitor).
     
    timer_stop(1);
     
    This will display the time it took to run the search.
     
    All together you could output something like:
     
    Your search for « coffee beans » returned « 16 » posts in « 0.87 » seconds.

  5. Chris Murphy says

    Wow. It’s a lot simpler than that to count WordPress’ search results, here:

        global $wp_query;
        $count = sizeof( $wp_query->posts );
        echo"<pre>";
        //var_dump($wp_query);// The WP Query Object
        var_dump($wp_query->posts); // The WP Query Object's 'posts' property (note the plural)
        echo"</pre>";
    

    If you drop that snippet in your search template, it will output the properties of the ‘$wp_query’ variable, specifically the ‘posts’ property of the object. This is an array that stores a collection of the returned posts from the search query, which you can do a number of things with once you access it, including (*drumroll*), *count* the number of posts in that array using either PHP’s ‘count()’ or ‘sizeof()’ functio

    • Ilya says

      Chris,

      This won’t work. The point is to find out the total number of results matching the query — not the number currently fetched. If there are more results than « fits » within a page, your code will only get number of elements on a page.

    • Editorial Staff says

      This code is correct. It works, the only issue he is pointing out is that it can be done differently as well. We have used this code on a client’s website and it works.

      Administrateur

  6. Konstantin says

    Good idea. Bad execution.
    Why in the world would you want to translate a span tag???
    And my favorite: _e(''); Huh??
    Why would you want to query the same search twice?
    Doesn’t make sense at all.

    But I don’t want to hate, this is how it should be done (in my humble opinion):


    post_count); ?>

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.