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

Como exibir postagens populares por visualizações no WordPress (2 maneiras)

Nota editorial: Ganhamos uma comissão de links de parceiros no WPBeginner. As comissões não afetam as opiniões ou avaliações de nossos editores. Saiba mais sobre Processo editorial.

Deseja exibir postagens populares com base em suas visualizações no WordPress?

Ao mostrar os posts mais populares do seu blog WordPress, você pode ajudar os leitores a encontrar o seu conteúdo melhor e mais valioso. Além disso, isso pode incentivá-los a permanecer mais tempo em seu site.

Neste artigo, mostraremos como exibir suas postagens populares por visualizações no WordPress.

How to Display Popular Posts by Views in WordPress

Por que exibir postagens populares por visualizações no WordPress?

Quando os usuários veem as publicações mais populares do seu blog WordPress, eles podem descobrir qual conteúdo os outros leitores mais gostam. Dessa forma, eles podem conferir esses artigos e participar da conversa.

Além disso, a exibição de seu conteúdo mais popular no WordPress pode aumentar sua prova social. É como dizer aos novos usuários: “Ei, outras pessoas acharam essas postagens muito úteis, e você também pode achar!”

WPBeginner's trending and popular posts

Por fim, mostrar as postagens mais populares do blog pode fazer com que as pessoas permaneçam mais tempo em seu site e explorem mais seu conteúdo.

Quanto mais o envolvimento do usuário aumenta, mais o Google acredita que seu conteúdo é bom e importante. Por sua vez, seu site pode ter uma classificação mais alta. Além disso, isso dá aos leitores mais tempo para converter, como assinar o seu boletim informativo.

Infelizmente, o WordPress não tem um recurso ou bloco incorporado para exibir suas postagens mais populares por exibições de página. Neste guia, mostraremos como fazer exatamente isso com um plugin e com código.

Basta clicar em um dos links rápidos abaixo para ir direto ao seu método preferido:

Tutorial em vídeo

Subscribe to WPBeginner

Se você preferir instruções escritas, continue lendo.

Método 1: Exibir postagens populares do WordPress por visualizações com o MonsterInsights

A maneira mais fácil de exibir postagens populares por visualizações no WordPress é com um plug-in. Na verdade, há muitos plug-ins de publicações populares disponíveis no WordPress, mas, em nossa opinião, a melhor opção é o MonsterInsights.

The MonsterInsights Google Analytics plugin

Usado por mais de 3 milhões de sites em todo o mundo, o MonsterInsights é o melhor plug-in do Google Analytics para WordPress. Embora sua principal funcionalidade seja a análise, ele também tem um recurso fácil de usar para mostrar suas postagens mais populares.

Em primeiro lugar, você precisará instalar o plug-in MonsterInsights e conectá-lo à sua conta do Google Analytics. Para obter mais detalhes, consulte nosso guia passo a passo sobre como instalar o Google Analytics no WordPress para iniciantes.

Observação: Embora haja uma versão gratuita do MonsterInsights disponível, usaremos a versão Pro, pois ela inclui o recurso de publicações populares.

Escolha um tema para owidget de postagens populares

Depois de ativar e configurar o plug-in, vá para Insights ” Popular Posts no painel do WordPress. Em seguida, clique no item de menu “Popular Posts Widget”.

The Popular Posts Widget in MonsterInsights

Rolando para baixo, você precisará selecionar um tema para exibir o widget de postagens populares. Há várias opções.

Alguns incluem uma imagem em destaque para a postagem, enquanto outros têm uma aparência mais minimalista.

Choosing a popular posts widget theme in MonsterInsights

Se quiser ver a aparência do tema antes de fazer sua escolha, basta descer na página até a seção Theme Preview (Visualização do tema).

Você também pode visualizar o tema em um formato Wide (amplo) ou Narrow (estreito). Com o formato Wide (amplo), você verá suas publicações listadas sob o conteúdo da página ou da publicação, enquanto o formato Narrow (estreito) exibe as publicações no lado direito, como uma barra lateral.

Previewing the popular posts widget theme in MonsterInsights

Em seguida, role a tela para baixo até a seção “Customize Design”. Aqui, você pode modificar as cores do tema, o tamanho da fonte, o layout e a contagem de postagens a serem exibidas.

As opções de personalização aqui podem variar dependendo do tema que você usar. Portanto, não deixe de explorar os diferentes temas para ver qual é o mais adequado para você.

Customizing the popular posts widget theme in MonsterInsights

Configurar o comportamento do widget Popular Posts

Depois de configurar o design do tema, você deve ir para a seção Behavior (Comportamento). É aqui que você controlará como o widget de postagens populares aparecerá em seu site do WordPress.

Nas configurações de Estilo do widget, você pode optar por usar o design que criou acima ou optar por não estilizar o widget. Com a segunda opção, o widget seguirá o CSS do tema de seu site WordPress.

Em seguida, você pode escolher como o widget deve escolher suas postagens mais populares. Aqui, escolha “Curated”.

Some of the popular posts widget's behavior settings in MonsterInsights

O que você precisa fazer em seguida é ativar a opção “Adicionar os 5 principais posts do Google Analytics” abaixo. Mas antes de fazer isso, você precisará do MonsterInsights Dimensions Add-On e adicionar o tipo de post como uma nova dimensão personalizada.

Isso permitirá que o MonsterInsights escolha as postagens mais populares com base nos dados do Google Analytics.

Para fazer isso, você precisa fazer o download do MonsterInsights Dimensions Add-on e instalá-lo como um plug-in no WordPress. Para obter instruções passo a passo, consulte nosso guia sobre como instalar um plug-in do WordPress.

Em seguida, vá para Insights “ Configurações e mude para a guia “Conversões”. Depois disso, clique em “Add New Custom Dimension” (Adicionar nova dimensão personalizada).

Adding a new custom dimension in MonsterInsights

Depois de fazer isso, selecione “Post type” (Tipo de postagem) no menu suspenso.

Isso permitirá que o MonsterInsights rastreie o desempenho de suas postagens de blog e outros tipos de postagens personalizadas.

Selecting post type as a custom dimension in MonsterInsights

Agora, basta retornar a Insights ” Popular Posts e ir para ‘Popular Posts Widget’.

Basta ativar o botão de alternância “Add Top 5 Posts from Google Analytics”. Em seguida, clique em “Test Automated Posts” para ver se a configuração foi bem-sucedida.

Adding top 5 posts based on GA data in MonsterInsights

Se sim, você verá uma mensagem pop-up de sucesso.

Ele deve dizer: “Os dados do Popular Posts podem ser obtidos corretamente. Observação: dependendo de quando você definiu as configurações de dimensões personalizadas, pode levar até sete dias para que os dados relevantes de Popular Posts sejam carregados pelo Google Analytics”.

Popular posts data can be fetched correctly popup message in MonsterInsights

Passando para as próximas etapas, agora você pode adicionar um título que aparecerá acima do widget. Ele pode ser algo como “Confira nossas publicações mais populares” ou algo semelhante.

Abaixo disso, você pode escolher se o widget deve ser exibido em todos os tipos de post, ser excluído de posts específicos e/ou aparecer somente em determinadas categorias de post.

Essas configurações são úteis se você tiver tipos de post personalizados que não sejam posts de blog e achar que o widget de posts populares parecerá irrelevante.

More behavior settings for the popular posts widget in MonsterInsights

Uma das últimas etapas é incorporar o widget de postagens populares. Há várias opções: colocá-lo automaticamente, usando um bloco do Gutenberg, adicionando-o como um widget da barra lateral ou usando um shortcode.

Vamos examinar cada opção uma a uma.

The embed options of popular posts widget in WordPress

Incorporar o widget de postagens populares automaticamente

O posicionamento automático é recomendado se você quiser que o widget seja exibido em todas as postagens que correspondam às configurações de comportamento que você definiu anteriormente.

Para isso, basta ativar o botão Automatic Placement (Colocação automática).

Activating automatic placement for the popular posts widget in MonsterInsights

A desvantagem dessa opção é que você não pode ajustar o design do widget com base no que fica melhor no post ou na página. Se precisar desse tipo de funcionalidade, você pode tentar o próximo método.

Incorporar o bloco Popular Posts em uma página ou postagem

Se quiser ter mais controle sobre a aparência do widget em uma página ou publicação, esse método é para você.

Primeiro, acesse o editor de blocos do post ou da página onde você deseja que o widget fique. Depois disso, clique no botão “+” adicionar bloco em qualquer lugar do editor e procure o bloco Popular Posts.

Adding MonsterInsights' popular posts block in the WordPress block editor

No painel de configurações do Block, você verá que há opções para alterar o tema, o tamanho da fonte, as cores, o título, o layout e a contagem de posts do widget.

Essas configurações são semelhantes às que vimos no plug-in MonsterInsights.

MonsterInsights' popular posts block settings in the WordPress block editor

A única diferença é que você não pode alterar quais publicações são escolhidas no widget.

Dito isso, nas Behavior Settings (Configurações de comportamento), é possível mostrar somente publicações de determinadas categorias. Dessa forma, você pode tornar as opções de postagens populares mais adaptadas às suas necessidades.

Choosing to only display posts from certain categories in the MonsterInsights popular posts widget

Quando você estiver satisfeito com as configurações do bloco, basta clicar no botão “Update” (Atualizar) no editor de posts e páginas.

Veja a seguir a aparência do bloco Popular Posts em nosso site de teste:

Example of what the MonsterInsights popular posts block look like on the WordPress site

Incorporar o widget Popular Posts em uma barra lateral

Se estiver usando um tema do WordPress que não seja de bloco e que tenha uma área da barra lateral pronta para widgets, você poderá adicionar o widget Popular Posts a ela.

Tudo o que você precisa fazer é ir para Appearance ” Widgets. Em seguida, clique no botão “+” adicionar widget na área da barra lateral e procure o widget Popular Posts – MonsterInsights.

Adding the MonsterInsights popular posts widget to the sidebar area

Como no método anterior, o widget inclui configurações semelhantes para personalizar a aparência do seu tema.

A diferença é que a interface é um pouco mais complicada de usar. À medida que você altera as configurações, não é possível ver a aparência real do widget. Você terá que clicar em um widget diferente ou em outra área para visualizá-lo.

Se você estiver satisfeito com a aparência do widget, basta clicar em “Update” (Atualizar) no canto superior direito.

Updating the sidebar area after adding the MonsterInsights popuplar posts widget

Não deixe de acessar seu site para verificar se a barra lateral está correta.

Veja como é o nosso:

Example of the MonsterInsights popular posts widget in a sidebar

Incorporar o widget Popular Posts com um código curto

A última opção é usar um shortcode. Esse método é recomendado se as opções acima não funcionarem para seu caso de uso específico.

Na guia Popular Posts Widget, role até a seção “Embed Options” (Opções de incorporação). Em seguida, escolha “Display using a Shortcode” (Exibir usando um código curto) e clique no botão “Copy Shortcode” (Copiar código curto).

Copying the popular posts widget shortcode in MonsterInsights

Depois disso, basta colocar o shortcode onde você quiser. Para obter mais informações, consulte nosso guia sobre como adicionar códigos de acesso no WordPress.

Método 2: Exibir postagens populares do WordPress por visualizações com o código

O método MonsterInsights é a maneira mais fácil de exibir seu conteúdo mais popular e melhor por visualizações no WordPress. Mas se você se sentir confortável com a codificação, também poderá usar o código para mostrar suas postagens mais populares no WordPress.

Para esse método, recomendamos o uso de um plug-in de snippets de código, como o WPCode, que é o que usaremos neste guia.

WPCode - Best WordPress Code Snippets Plugin

O WPCode torna segura a inserção de código personalizado sem interagir diretamente com seus arquivos do WordPress. Além disso, como esse método requer o uso de vários snippets de código, o plug-in facilitará muito o gerenciamento e o rastreamento de todos eles.

Primeiro, você precisa instalar o WPCode no WordPress. Há uma versão gratuita do WPCode disponível, mas usaremos a versão Pro, pois ela vem com os recursos necessários para inserir o código nos locais corretos.

Para obter um guia de instalação passo a passo, leia nosso artigo sobre como instalar um plug-in do WordPress.

Adicionar a função de contador de visualizações de postagens do WordPress

Após a ativação do plug-in, você precisa ir para Code Snippets ” + Add Snippet no painel. Em seguida, passe o mouse sobre “Add Your Custom Code (New Snippet)” e clique em “Use snippet”.

Use snippet

Agora, você está no editor de snippet de código do WPCode. Antes de inserir qualquer código, vá em frente e adicione um título para o snippet.

Para esse primeiro código, você pode nomeá-lo como “WordPress Post Views Counter Function”. Isso ocorre porque o objetivo desse primeiro código é criar uma função para contar as visualizações de posts no WordPress.

Em seguida, altere o Tipo de código para “PHP Snippet”. Observe que todos os trechos de código que você terá de adicionar a partir deste artigo estão em PHP.

Creating the WordPress Post Views Counter Function in WPCode

Depois disso, você pode copiar e colar o seguinte código abaixo:

function wpb_set_post_views($postID) {
    $count_key = 'wpb_post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}
//Get rid of prefetching to keep the count accurate
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

Agora, role para baixo até a seção “Insertion” (Inserção) e selecione “Auto Insert” (Inserção automática) para o método de inserção e “Run Everywhere” (Executar em todos os lugares) para o local. Isso funciona da mesma forma que inserir o código no arquivo functions.php do seu tema.

Depois disso, navegue até o lado superior direito da página e torne o código ativo.

Em seguida, clique em “Save Snippet”.

Choosing the insertion method and location in WPCode

Nessa etapa, você precisa adicionar outro novo snippet de código personalizado. Você pode chamá-lo de “Track Post Views Function Call”.

Esse código chamará a função acima e a ativará em suas páginas de postagem única.

Depois de fazer isso, copie e cole o seguinte snippet:

wpb_set_post_views(get_the_ID());

O que é diferente nesse snippet de código é que você escolherá o local “Insert After Post” (Inserir após a postagem) porque ele deve ser executado nas páginas de postagem única.

Choosing Insert After Post as the code insertion location in WPCode

Quando terminar, basta tornar o código ativo e salvá-lo.

Inserir o gancho de rastreamento de visualizações de posts do WordPress

Agora, você precisa adicionar um novo trecho de código que verifica se a página atual é uma única postagem. Em caso afirmativo, ele chamará a função de contador de visualizações de posts do WordPress para rastrear e atualizar a contagem de visualizações do post.

Dessa forma, toda vez que um usuário visitar a postagem, sua contagem de visualizações será atualizada.

Vamos chamar esse snippet de ‘WordPress Post Views Tracking Hook’. Em seguida, insira as seguintes linhas de código:

function wpb_track_post_views ($post_id) {
    if ( !is_single() ) return;
    if ( empty ( $post_id) ) {
        global $post;
        $post_id = $post->ID;    
    }
    wpb_set_post_views($post_id);
}
add_action( 'wp_head', 'wpb_track_post_views');

Você pode escolher o método de inserção como “Auto Insert” e o local como “Frontend Only”.

Da mesma forma que nas etapas anteriores, basta ativar o código e salvar o snippet.

Choosing Frontend Only as the code insertion location in WPCode

Observação: se você estiver usando um plug-in de cache, essa técnica pode não funcionar por padrão. Você pode usar o recurso de cache de fragmentos oferecido por alguns plug-ins de cache, como o W3 Total Cache, para que ela funcione.

Adicionar funções para recuperar a contagem de visualizações de posts e exibir os posts mais populares com contagens de visualizações

Estamos agora nas etapas finais deste guia. Você precisa adicionar um trecho de código que recupere e formate o número de visualizações de uma determinada postagem do WordPress. Isso será útil mais tarde ao exibir a lista das postagens mais visualizadas.

Você pode nomear esse código como “Retrieve Post Views Count Function” e definir o local como “Run Everywhere”.

Aqui está o trecho de código:

function wpb_get_post_views($postID){
    $count_key = 'wpb_post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "0 View";
    }
    return $count.' Views';
}

Novamente, certifique-se de tornar o código ativo no WPCode e salvá-lo depois.

Depois de fazer isso, crie um novo snippet de código novamente e nomeie-o como “Display Most Popular Posts with View Counts”. Esse é o código que mostrará suas postagens mais populares na parte inferior das postagens do blog.

Na caixa Code Preview, insira o seguinte trecho de código:

// Customize the query parameters as needed
$popularpost = new WP_Query( array(
    'posts_per_page' => 3,         // Feel free to adjust the number of posts to display
    'meta_key' => 'wpb_post_views_count',
    'orderby' => 'meta_value_num',
    'order' => 'DESC'
));
?>

<div class="popular-posts">
    <h2>See Our Most Popular Posts</h2> <!-- Feel free to customize the title -->
    <ul>

    <?php while ( $popularpost->have_posts() ) : $popularpost->the_post(); ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
            - <?php echo wpb_get_post_views(get_the_ID()); ?>
        </li>
    <?php endwhile; ?>

    </ul>
</div>

<?php wp_reset_postdata(); 

Conforme observado no código, fique à vontade para ajustar o número de publicações a serem exibidas e personalizar o título dessa seção.

Na seção WPCode Insertion (Inserção de código WPC), certifique-se de selecionar “Insert After Post” (Inserir após a postagem) para o local. Em seguida, basta tornar o código ativo e salvar o snippet.

Tudo o que resta a fazer agora é visitar uma das postagens do seu blog e ver se o código funciona. Veja como são as publicações mais populares por seção de visualizações em nosso blog de teste do WordPress:

What the most popular posts by views section looks like made with WPCode

Dica de especialista: Para ver se seu código funciona sem alterar permanentemente seu site, você pode experimentar o Modo de teste do WPCode.

Esse recurso permite que você adicione seus códigos normalmente e somente você pode ver como eles são no front-end. Por outro lado, seus usuários interagirão com seu site normalmente.

Esperamos que este artigo tenha ajudado você a aprender como exibir posts populares por visualizações no WordPress. Talvez você também queira conferir nosso artigo sobre como exibir produtos populares no WooCommerce e nosso guia para iniciantes sobre campos personalizados do WordPress.

Se você gostou deste artigo, inscreva-se em nosso canal do YouTube para receber tutoriais em vídeo sobre o WordPress. Você também pode nos encontrar no Twitter e no Facebook.

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

166 ComentáriosDeixe uma resposta

  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. Bigdragon13th says

    Hello,
    I’ve using this code for months and it’s work greats! That’s until I start using W3 Total Cache and this code stop count views for me.
    I’m struck at where do I need to put the mfunc to let the code work with cache. Can you point that out?
    FYI, I put all the code in a site-specific plugin.

  3. leslie says

    hello, I have some problem on how setting up like when the login user won’t include on the count while viewing any pages?? how to do that.. please need some help on these. thanks

  4. Sarah says

    Hey there, thanks for this. REALLY helpful!! Would you know how to apply a time range to this code? For example to show the most popular posts in the last day, week or month etc? I know there are plugins for this but I would like to do it without one :)

  5. Denis says

    Hello,
    thanks for this nice tutorial. It works on my page!

    – how can I exclude robots and spiders that hit my posts?
    – May be I can set a timer of 10 seconds. after that the count should rise. So the people who only click thourgh the posts are not counted.

    Cheers,
    Denis

  6. Jenni B says

    Hello – thanks so much for this! I noticed the question regarding the W3TC workaround, but have a slightly different question: does that still apply if I’m hooking into wp_head from functions.php, and if so, how exactly do I implement it there? Thank you!

  7. Kosmos says

    Hello, thanks for this snippet.

    I have a problem, the orderby don’t work. I have five posts :
    – Post 1 : 85 views
    – Post 2 : 35 views
    – Post 3 : 165 views
    – Post 4 : 1 view
    – Post 5 : 1 view

    When i displayed it the order was : 1, 2, 4, 5 and 3

    Do you have an idea please ?

  8. Iftekhar says

    following your article I am using post view count in my site since 6 months. It was working fine, but recently I am having problem with this. If a visitor view a post the count is increasing by 1 but the problem is the count is increasing in all other posts. I have w3 total installed and I m using mfunc according to your article. Please help me if you have any idea about this issue… Thanks.

  9. ivan says

    Hello,
    I am wanting to switch from using the plugin because it doesn’t support the polylang language (the author’s not getting back to me and I don’t really know if it’s possible to filter functions for the plugin..)
    Two questions:
    – I examined the code a bit and I’m not sure if this code starts counting posts from when it’s implemented? Or does it somehow retrieve where the post counts are currently?
    – The current code on this website uses the get_posts() function so it creates an args array instead of using WP_Query(). Is this the same thing? I’m guessing not. And if it isn’t is the code below correct to get the array? I tried implementing this but it didn’t seem to work.
    $args = array( ‘meta_key’ => ‘wpb_post_views_count’, ‘orderby’ => ‘meta_value_num’, ‘order’ => ‘DESC’,’numberposts’ => 6, ‘post_status’=>”publish”,’post_type’=>”post”,’lang’ => ‘en’);
    thanks!

  10. Tomas says

    This approach is very basic. If you want to count clicks from the same user (same IP) only every 5 minutes or 10 minutes etc. you need to have a separate table for that and before adding a new row in db you need to check the ip and time. If there is a record saved 3 minutes ago, the click is not added. Otherwise, it is added. Also this aproach allows you to create custom list of most viewed articles in 7 dyas, month, all time etc. Or even by category, user etc. (if you store appropriate values in appropriate table columns.

  11. boson says

    i am trying .. when you say put code wpb_set_post_views(get_the_ID()); inside of single post loop, does that mean use this code inside of the theme single.php anywhere?
    thank you for your help

  12. Cory Dobson says

    Is there a way of restricting when the post views are collected from? For example, I am looking to display the posts with the most views in the last 24 hours, how would you do something like that using this code?

    Great post by the way, really helpful!

  13. Mark says

    What if your single-xxxx.php doesn’t use the loop but custom fields. How can I use this code if I don’t use the loop?

  14. George says

    Thanks for this post! Really really good.
    I’ve two question:

    1. Is there any possibility to count just one visit for each IP adress? How?.
    2. Can i show the most popular posts by a specific period of time? For example, most visited posts this month, or the most popular posts from 1 of may to 1 of june…

    Thank you!

  15. shishir umrao says

    Hi,
    This code is working but whenever i reload the page , it is adding “2” to the total page count. For example if page count is 14 and after reloading total page count is 16 … can anyone guess where’s the problem ?

    Shishir Umrao

  16. Nick says

    Very useful post, I managed to make my Tag pages to order posts by a custom field value similar to post view count, however, I ave pagination on my tag pages and it keeps showing the same top ranking posts on all pages, even after I have removed this code:

    ‘posts_per_page’ => 4,

    How do I fix the pagination so it show other posts on subsequent Tag pages?

    • Chris says

      How did you manage to make your Tag pages order posts by a custom field value similar to post view count?

      It looks like the popular posts plugin only takes categories as a parameter.

  17. Mike says

    Thanks for the very detailed instructions. Will using this to display the most popular posts cause a lot of additional server load if a site has significant traffic? Some of the WP plugins for this sort of thing tend to have this problem.

  18. Lowell says

    I’m still learning this stuff so pardon my ignorance.

    How do you allow the user to choose between queries like they do on codecanyon when they allow you to sort by price, sales, date etc.?

    Thanks so much.

  19. Ar Ya says

    Hi , that’s great !
    But ‘orderby’ => ‘wpb_post_views_count meta_value_num’ not working.
    please use : ‘orderby’ => ‘meta_value_num’
    thnx

  20. nick says

    Thanks, it works for me, just with one important exception – popular posts are not as links, just their titles. How can I fix this, please?

  21. Preston says

    I added this code in the manner described in the article and upon activation, I saw this….

    The plugin generated 2 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.

    • Preston says

      Fixed. I did two things:

      1. Switched my permalink structure to a custom structure /%category%/%postname%/
      2. Check through all of my pages for extra spaces.

      One of them worked.

      …go figure

      Preston

  22. Jose Vega says

    Hi, I think it´s necesary add – wp_reset_query(); – at the end of the query to destroys the previous query used on a custom Loop.

    I hope It helps somebody.

  23. Jon Edwards says

    I have this working to 95% using a custom WP Query to display popular posts from each category.

    The only bit not working for me is the order – mine won’t display in descending order of views.

  24. Cameron says

    Thanks for the post! This really helped.

    I’m not sure if anyone else ran into this issue, but when you set up the arguments for WP_Query, you have orderby => ‘wpb_post_views_count’. This was a problem for me because I wasn’t sure how it was ordering my posts. In the codex it says that if your using numbers they will only sort by the first digit. To fix this, you can simply replace the ‘wpb_post_views_count’ with ‘meta_value_num’. This basically will tell the query to reach inside the post’s meta value and probably cast it to an integer before it sorts. Hope this helps anyone running into the same issues.

    Overall, it works great! I have the 4 most popular posts in a slider on the home page. Thanks again!

      • efishinsea says

        Hi. Your code sample up top is *not * updated.

        Instead of this:

        ‘orderby’ => ‘wpb_post_views_count meta_value_num’

        you should have this as suggested :

        ‘orderby’ => ‘meta_value_num’

        if you want to sort by “Most to Least”

  25. Kris says

    This looks great on my home page but it seem to want to display on my single.php or anywhere else on my site. I tried creating a sidebar-single.php and inserting the code but still no luck. Any idea why it wouldn’t work on other areas my theme?

    • Mody says

      This usually happens when meta key wpb_post_views_count is not available for posts, make sure you add the function that tracks views within wp while loop, otherwise it will keep showing random posts.

      – Mody

      • Bent says

        Hello,
        I’m using your code for track post view in the wordpress theme.

        function wpb_get_post_views($postID){
        $count_key = ‘wpb_post_views_count’;
        $count = get_post_meta($postID, $count_key, true);
        if($count==”){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, ‘0’);
        return “0 View”;
        }
        return $count.’ Views’;
        }

        The problem is that when I use W3 Total Cache the track view is not working right.

        Is there a way in the W3 Total Cache’s Options to put ignore only on this function, but in the same time I want the code to work with W3 Total Cache?

        Thank you!

  26. Vaibhav says

    Hello
    i followed your tutorials and have done exactly what u said.
    i also added ur snippet
    php query_posts(‘meta_key=post_views_count&orderby=meta_value_num&order=DESC’);
    in index.php

    i am facing a little error,
    i am using infinite scrolling
    when i put this snippet in index.php
    the infinite scroll instead of loading next set of post
    loads the same sets of post

    For better Understanding u can check it live here
    blog.newgags,com

    • Henry says

      I do apologise. I had added the tracker to both the WP header and also to the single post body. Very stupid on my part :}

      Nice tutorial, very easy to follow.

  27. Brandon says

    First of all thanks for this post. Second I have been using this script for a few days now and for some reason it started out fine and now it is not displaying the most viewed posts, I don’t see any rhyme or reason to what posts are now being displayed. The last I checked the post that it is displaying at the top has 8 page views. I know there are posts with 25+ recorded page views. I would like to figure this out. Can you possibly point me in the right direction. I followed this post word for word. The post views are being recorded properly.

  28. Einar Ólafsson says

    Hi. This works grade up until the view count gets over 999. All post with more view counts than 999 are not displayed, the query never post them. The latest post is the one with exactly 999 and the rest are under that. I have over 100 post that have more than thousand and are not being included.

  29. Martinbeasnunez says

    Guys you rockkk

    Quick question:
    If i have add a custom post type in your code ?
    (popular post from especific custom post type)

    Regards (:

  30. Artem Russakovskii says

    This is a good basic tutorial, but be warned: it’s not going to work if you use caching strategies that bypass PHP (like wp-supercache, W3TC, nginx/varnish, etc). The only way to count those would be via Javascript or log parsing.

    • Editorial Staff says

      Hey Artem, Thanks for dropping by. Actually using W3 Total Cache, you can use fragment caching and it works just fine. Going to update the article for those who are using the caching plugin.

      Administrador

      • Artem Russakovskii says

        Interesting. However, I run nginx in front of W3TC, and it does a whole lot of its own caching, so it’s always safer/more reliable to use an AJAX approach. Nice info on the fragment caching though, I had no idea W3TC had it.

  31. Ramon Fincken says

    Why use
    //To keep the count accurate, lets get rid of prefetching
    remove_action( ‘wp_head’, ‘adjacent_posts_rel_link_wp_head’, 10, 0); ?

    if you can use the main loop or the footer ?

    • Editorial Staff says

      Some browsers prefetch the rel links with the next value. So technically when a user views one post, it can act as if they had viewed both posts. This will cause inaccurate count. If you like inflated views, then don’t take it off.

      Administrador

      • Zach says

        Please stop saying stuff like this. Plugins aren’t bad, it’s articles like this that make them look bad. Enough articles have come out over the past few weeks to fully explain this – it’s getting a little embarrassing.

        • Editorial Staff says

          How would you suggest titling future posts instead? DIY prefix? These are different then just using a pre-made plugin. Also, if you read the article, there is no where in our article that we say “plugins are bad”. We clearly state that the only reason why coded this was to get more customization. It is up to a user to take either stance. Some can think that plugins are bad… whereas others like yourself can think that we are saying that plugins are bad…

        • Zach says

          I don’t think any type of prefix is needed. It’s one of the great/scary things about WordPress. You COULD put this code in your theme, but then begs the argument about needing to either, 1) Loose those customizations when you change your theme, or 2) have the knowledge to properly pull those over to another theme.

          A lot of the users here are beginners (hence the point of this site), so many will just copy/paste what you give them. WP Beginner is obviously a fantastic resource (reason why I follow you on Twitter), but you have a responsibility to not put a false notion about how plugins/themes work.

          Correct, you don’t flat out say, “Plugins are bad, put this in your theme instead!”, but the original commenter to the thread I replied to, said, “Yay! A tutorial that doesn’t require a plugin!” – so even though you didn’t say it, that’s how it was taken.

          I’d suggest doing was Pippin does for his plugins – he has a simple starter plugin he uses for all of his tutorials. Why not create a blank “Starter Plugin” download, with just the basics, so others can download and put their customizations in there instead? Reference it in each article you do and it takes out some of the confusion. Thanks.

        • Editorial Staff says

          We have been following Otto’s advice on site-specific plugin for quite some time. It is probably similar to what Pippin does. If you read this article, site-specific plugin is hyperlinked. It is in most other articles as well. That article shows users the importance of site-specific plugin and advise users to not put everything in functions.php file. At the bottom of that article, the sample “starter plugin” is there for anyone to start with.

        • codekipple says

          In fairness this tutorial helped me out. I wanted a simple solution for popular posts after trying some of the plugins and not being able to fully control the markup. This tutorial helped me quickly implement some popular posts functionality into my own plugin.

          So i agree that using pre-built plugins is not a bad thing, but at times tutorials like this are useful to take control and build out a plugin that works the way you need it to instead of fighting against an already built plugin.

    • Pippin says

      As Zach said, please stop using “without a plugin”. Sure, it’s cool to see how to code this yourself but there is literally no difference between this code and the code in a plugin. You could place this code into a plugin and it would function identically to placing it in your theme.

      • Ruben says

        If you say there’s no difference, you have no idea what you’re talking about. Lets say your are working on a site and don’t have access to the plugins directory, making a solution that works “without using a plugin” would be a viable alternative.

        As for the title, semantically the title should reflect the content of the post and could be “How to Display Popular Posts by Views in WordPress with or without a Plugin”.

        However, taking SEO in to consideration, lets say he would like this post to reach a specific audience, for example, people who don’t want to or can’t use a plugin, the title would probably be best as is.

  32. Gautam Doddamani says

    i am using genesis child theme..can u tell me which all functions and codes to use..i am sorry i am a noob to genesis…

      • Gautam Doddamani says

        is it true? as artim told, does this code become unresponsive when we use a caching plugin?? for example i currently use W3 total cache and i want to use this method to build my custom popular post by views widget…i read this kind of post on wpsnipp.com and the users suggested it does not work when we enable caching plugins…reply soon…

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.