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

Exibir termo de pesquisa e contagem de resultados no WordPress

Neste tutorial, compartilharemos como você pode adicionar uma função simples em sua página de pesquisa que exibirá o termo de pesquisa e o número de resultados. Esse recurso foi uma solicitação especial de um de nossos usuários por e-mail. Se você quiser que abordemos um tópico, fique à vontade para fazer uma sugestão.

Displaying search term and result count in WordPress search

Abra o arquivo search.php em seu tema e adicione o seguinte código:

<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>

O código acima exibirá algo parecido com isto:

Resultado da pesquisa para twitter – 15 artigos

Você também pode destacar o termo de pesquisa adicionando a classe CSS .search-terms à folha de estilo do seu tema. Aqui está um CSS simples para você começar:

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

Essa é apenas uma das coisas interessantes que você pode fazer na página de pesquisa ao personalizá-la. Você também pode destacar termos de pesquisa nos resultados e até mesmo adicionar um recurso de pesquisa por categoria à sua pesquisa do WordPress.

Fonte: Michael Martin

Divulgação: Nosso conteúdo é apoiado pelo leitor. Isso significa que, se você clicar em alguns de nossos links, poderemos receber uma comissão. Veja como o WPBeginner é financiado, por que isso é importante e como você pode nos apoiar. Aqui está nosso processo editorial.

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.

O kit de ferramentas definitivo WordPress

Obtenha acesso GRATUITO ao nosso kit de ferramentas - uma coleção de produtos e recursos relacionados ao WordPress que todo profissional deve ter!

Reader Interactions

16 ComentáriosDeixe uma resposta

  1. Syed Balkhi

    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

    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

    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

    • Marco

      Next time I take a close look to the comments. CHADHAYTON already posted a link how you can handle it now.

  4. Henry

    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.

    • jameslhf

      Thank you Henry, that helped me! :)

    • Prasanna

      Thanks Henry. This helped me a lot.

  5. Chris Murphy

    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

    • Editorial Staff

      Your code is cut off a little. Is there a way that you can email us the snippet and we can try it and write about it. Obviously full credit will be given to you.

      Administrador

    • Ilya

      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.

  6. pete

    Search results are a personal thing from a user so it’s good if they are given lots of info for them.

  7. basilakis

    So the code is right or not? :)

    I see Konstantin has some point about the query, but the comments “ate” the results! :D

    • Editorial Staff

      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.

      Administrador

  8. Konstantin

    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); ?>

  9. Tom

    I really don’t give my on page search enough thought. Something like this is great because it makes the page more personalised.

Deixe uma resposta

Obrigado por deixar um comentário. Lembre-se de que todos os comentários são moderados de acordo com nossos política de comentários, e seu endereço de e-mail NÃO será publicado. NÃO use palavras-chave no campo do nome. Vamos ter uma conversa pessoal e significativa.