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

Come visualizzare i post più popolari in base alle visualizzazioni in WordPress (2 modi)

Nota editoriale: guadagniamo una commissione dai link dei partner su WPBeginner. Le commissioni non influenzano le opinioni o le valutazioni dei nostri redattori. Per saperne di più su Processo editoriale.

Volete visualizzare i post più popolari in base alle loro visualizzazioni in WordPress?

Mostrando i post più popolari del vostro blog WordPress, potete aiutare i lettori a trovare i vostri contenuti migliori e di maggior valore. Inoltre, potete incoraggiarli a rimanere più a lungo sul vostro sito web.

In questo articolo vi mostreremo come visualizzare i post più popolari in base alle visualizzazioni in WordPress.

How to Display Popular Posts by Views in WordPress

Perché visualizzare i post più popolari in base alle visualizzazioni in WordPress?

Quando gli utenti vedono i post più popolari del vostro blog WordPress, possono scoprire quali sono i contenuti più apprezzati dai loro colleghi lettori. In questo modo, possono controllare gli articoli e partecipare alla conversazione.

Inoltre, la visualizzazione dei contenuti più popolari in WordPress può aumentare la vostra riprova sociale. È come dire ai nuovi utenti: “Ehi, altre persone hanno trovato questi post molto utili, e potresti farlo anche tu!”.

WPBeginner's trending and popular posts

Infine, mostrare i post di tendenza del blog può far sì che le persone rimangano più a lungo sul vostro sito web ed esplorino maggiormente i vostri contenuti.

Più aumenta il coinvolgimento degli utenti, più Google ritiene che i contenuti siano validi e importanti. Di conseguenza, il vostro sito può posizionarsi più in alto. Inoltre, i lettori hanno più tempo per convertire, ad esempio iscrivendosi alla vostra newsletter.

Purtroppo, WordPress non ha una funzione o un blocco integrato per visualizzare i post più popolari in base alle visualizzazioni di pagina. In questa guida vi mostreremo come fare esattamente questo con un plugin e con il codice.

Basta cliccare su uno dei link rapidi qui sotto per passare direttamente al metodo preferito:

Video tutorial

Subscribe to WPBeginner

Se preferite le istruzioni scritte, continuate a leggere.

Metodo 1: Visualizzare i post più popolari di WordPress in base alle visualizzazioni con MonsterInsights

Il modo più semplice per visualizzare i post popolari in base alle visualizzazioni in WordPress è un plugin. Esistono molti plugin per i post popolari di WordPress, ma a nostro avviso la scelta migliore è MonsterInsights.

The MonsterInsights Google Analytics plugin

Utilizzato da oltre 3 milioni di siti web in tutto il mondo, MonsterInsights è il miglior plugin di Google Analytics per WordPress. Sebbene la sua funzionalità principale sia l’analisi, ha anche una funzione facile da usare per mostrare i post più popolari.

Per prima cosa è necessario installare il plugin MonsterInsights e collegarlo al proprio account Google Analytics. Per maggiori dettagli, consultate la nostra guida passo-passo su come installare Google Analytics in WordPress per i principianti.

Nota: sebbene sia disponibile una versione gratuita di MonsterInsights, noi utilizzeremo la versione Pro poiché include la funzione dei post popolari.

Scegliere un tema peril widget dei post più popolari

Una volta attivato e configurato il plugin, andare su Insights ” Popular Posts dalla dashboard di WordPress. Quindi, fate clic sulla voce di menu “Widget dei messaggi popolari”.

The Popular Posts Widget in MonsterInsights

Scorrendo verso il basso, è necessario selezionare un tema per visualizzare il widget dei post popolari. Ci sono varie opzioni.

Alcuni includono un’immagine in evidenza per il post, mentre altri hanno un aspetto più minimale.

Choosing a popular posts widget theme in MonsterInsights

Se si desidera vedere l’aspetto del tema prima di fare la propria scelta, basta spostarsi in fondo alla pagina fino alla sezione Anteprima del tema.

È inoltre possibile visualizzare l’anteprima del tema in formato Wide o Narrow. Con il formato Wide, i post sono elencati sotto il contenuto della pagina o del post, mentre il formato Narrow li visualizza sul lato destro, come una barra laterale.

Previewing the popular posts widget theme in MonsterInsights

Quindi, scorriamo verso il basso fino alla sezione “Personalizza design”. Qui è possibile modificare i colori del tema, la dimensione dei caratteri, il layout e il numero di post da visualizzare.

Le opzioni di personalizzazione possono variare a seconda del tema utilizzato. Quindi, assicuratevi di esplorare i diversi temi per vedere quello più adatto a voi.

Customizing the popular posts widget theme in MonsterInsights

Configurare il comportamento del widget dei post più popolari

Una volta configurato il design del tema, è necessario andare alla sezione Comportamento. Qui si controllerà il modo in cui il widget dei post popolari apparirà sul vostro sito WordPress.

Nelle impostazioni di Widget Styling, si può scegliere di utilizzare il design realizzato in precedenza o di non creare alcuno stile per il widget. Con la seconda opzione, il widget seguirà il CSS del tema del vostro sito WordPress.

Poi si può scegliere come il widget deve scegliere i post più popolari. Qui, scegliete “Curato”.

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

La prossima cosa da fare è attivare l’opzione “Aggiungi i 5 post più importanti da Google Analytics”. Prima di farlo, però, è necessario utilizzare l’Add-On MonsterInsights Dimensions e aggiungere il tipo di post come nuova dimensione personalizzata.

In questo modo MonsterInsights sceglierà i post più popolari in base ai dati di Google Analytics.

Per farlo, è necessario scaricare il componente aggiuntivo MonsterInsights Dimensions e installarlo come plugin in WordPress. Per istruzioni passo passo, consultate la nostra guida su come installare un plugin di WordPress.

Quindi, andare su Insights “ Impostazioni e passare alla scheda “Conversioni”. Quindi fare clic su “Aggiungi nuova dimensione personalizzata”.

Adding a new custom dimension in MonsterInsights

Una volta fatto ciò, selezionare “Tipo di post” nel menu a discesa.

Ciò consentirà a MonsterInsights di monitorare le prestazioni dei post del blog e di altri tipi di post personalizzati.

Selecting post type as a custom dimension in MonsterInsights

Ora è sufficiente tornare a Insights ” Popular Posts e andare su ‘Popular Posts Widget’.

È sufficiente attivare il pulsante “Aggiungi i 5 post più importanti da Google Analytics”. Quindi, fate clic su “Test dei post automatizzati” per verificare se l’impostazione è riuscita.

Adding top 5 posts based on GA data in MonsterInsights

In caso affermativo, verrà visualizzato un messaggio di successo.

Dovrebbe essere scritto: “I dati dei Post popolari possono essere recuperati correttamente. Attenzione: a seconda di quando sono state configurate le impostazioni delle dimensioni personalizzate, potrebbero essere necessari fino a 7 giorni per vedere il caricamento dei dati rilevanti dei post popolari da Google Analytics”.

Popular posts data can be fetched correctly popup message in MonsterInsights

Passando alle fasi successive, è possibile aggiungere un titolo che apparirà sopra il widget. Può essere qualcosa come “Scopri i nostri post più popolari” o qualcosa di simile.

In basso, si può scegliere se il widget deve essere visualizzato in tutti i tipi di post, se deve essere escluso da specifici post e/o se deve apparire solo in alcune categorie di post.

Queste impostazioni sono utili se si hanno tipi di post personalizzati diversi dai post del blog e si ritiene che il widget dei post popolari sia irrilevante.

More behavior settings for the popular posts widget in MonsterInsights

Uno degli ultimi passi consiste nell’incorporare il widget dei post popolari. Ci sono diverse opzioni: inserirlo automaticamente, usare un blocco Gutenberg, aggiungerlo come widget della barra laterale o usare uno shortcode.

Esaminiamo una per una tutte le opzioni.

The embed options of popular posts widget in WordPress

Incorporare automaticamente il widget dei post più popolari

Il posizionamento automatico è consigliato se si desidera che il widget venga visualizzato su tutti i post che corrispondono alle impostazioni di comportamento impostate in precedenza.

A tal fine, è sufficiente attivare il pulsante Posizionamento automatico.

Activating automatic placement for the popular posts widget in MonsterInsights

Lo svantaggio di questa opzione è che non è possibile regolare il design del widget in base all’aspetto migliore del post o della pagina. Se avete bisogno di questo tipo di funzionalità, potete provare il metodo successivo.

Incorporare il blocco dei messaggi popolari in una pagina o in un post

Se si desidera avere un maggiore controllo sull’aspetto del widget in una pagina o in un post, questo metodo fa al caso vostro.

Per prima cosa, accedere all’editor dei blocchi del post o della pagina in cui si desidera inserire il widget. Quindi, fare clic sul pulsante “+” per aggiungere un blocco in qualsiasi punto dell’editor e cercare il blocco Popular Posts.

Adding MonsterInsights' popular posts block in the WordPress block editor

Nel pannello delle impostazioni del blocco sono presenti opzioni per modificare il tema del widget, la dimensione dei caratteri, i colori, il titolo, il layout e il numero di post.

Queste impostazioni sono simili a quelle già viste nel plugin MonsterInsights.

MonsterInsights' popular posts block settings in the WordPress block editor

L’unica differenza è che non è possibile modificare i post che vengono scelti nel widget.

Detto questo, nelle Impostazioni di comportamento è possibile mostrare solo i post di determinate categorie. In questo modo, è possibile rendere la scelta dei post più popolari più adatta alle proprie esigenze.

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

Una volta soddisfatte le impostazioni del blocco, basta fare clic sul pulsante “Aggiorna” nell’editor di post e pagine.

Ecco come appare il blocco dei post popolari sul nostro sito web di prova:

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

Incorporare il widget dei post più popolari in una barra laterale

Se si utilizza un tema WordPress non bloccante che dispone di un’area della barra laterale predisposta per i widget, è possibile aggiungere il widget Popular Posts.

È sufficiente andare su Aspetto ” Widget. Quindi, fare clic sul pulsante ‘+’ per aggiungere un widget nell’area della barra laterale e cercare il widget Popular Posts – MonsterInsights.

Adding the MonsterInsights popular posts widget to the sidebar area

Come nel metodo precedente, il widget include impostazioni simili per personalizzare l’aspetto del tema.

La differenza è che l’interfaccia è leggermente più complicata da usare. Mentre si modificano le impostazioni, non è possibile vedere l’aspetto effettivo del widget. È necessario fare clic su un altro widget o su un’altra area per visualizzare l’anteprima.

Se siete soddisfatti dell’aspetto del widget, fate clic su “Aggiorna” nell’angolo in alto a destra.

Updating the sidebar area after adding the MonsterInsights popuplar posts widget

Assicuratevi di andare sul vostro sito web per verificare che la barra laterale sia corretta.

Ecco come si presenta il nostro:

Example of the MonsterInsights popular posts widget in a sidebar

Incorporare il widget dei post più popolari con uno shortcode

L’ultima opzione consiste nell’utilizzare uno shortcode. Questo metodo è consigliato se le opzioni precedenti non funzionano per il vostro caso specifico.

Nella scheda Popular Posts Widget, scorrere fino alla sezione ‘Embed Options’. Scegliere quindi “Visualizza utilizzando un codice breve” e fare clic sul pulsante “Copia codice breve”.

Copying the popular posts widget shortcode in MonsterInsights

Dopodiché, è sufficiente posizionare lo shortcode dove si preferisce. Per ulteriori informazioni, consultate la nostra guida su come aggiungere shortcode in WordPress.

Metodo 2: Visualizzare i post più popolari di WordPress in base alle visualizzazioni con il codice

Il metodo MonsterInsights è il modo più semplice per visualizzare i contenuti più popolari e migliori in base alle visualizzazioni in WordPress. Ma se vi sentite a vostro agio con la codifica, potete anche usare il codice per mostrare i vostri post più popolari su WordPress.

Per questo metodo, si consiglia di utilizzare un plugin per gli snippet di codice come WPCode, che è quello che utilizzeremo in questa guida.

WPCode - Best WordPress Code Snippets Plugin

WPCode rende sicuro l’inserimento di codice personalizzato senza interagire direttamente con i file di WordPress. Inoltre, poiché questo metodo richiede l’uso di più snippet di codice, il plugin renderà molto più semplice la gestione e il monitoraggio di tutti.

Per prima cosa, è necessario installare WPCode in WordPress. È disponibile una versione gratuita di WPCode, ma noi utilizzeremo la versione Pro, poiché è dotata delle funzioni necessarie per inserire il codice nei punti giusti.

Per una guida all’installazione passo passo, leggete il nostro articolo su come installare un plugin di WordPress.

Aggiungere la funzione di contatore delle visualizzazioni dei post di WordPress

Dopo l’attivazione del plugin, è necessario andare su Code Snippets ” + Add Snippet dalla dashboard. Quindi, passare il mouse su “Aggiungi il tuo codice personalizzato (nuovo snippet)” e fare clic su “Usa snippet”.

Use snippet

Ora ci troviamo nell’editor di snippet di codice di WPCode. Prima di inserire il codice, aggiungere un titolo allo snippet.

Per questo primo codice, si può dare un nome come “WordPress Post Views Counter Function”. Questo perché lo scopo di questo primo codice è creare una funzione per il conteggio delle visualizzazioni dei post in WordPress.

Quindi, cambiare il tipo di codice in “Snippet PHP”. Si noti che tutti gli snippet di codice che si dovranno aggiungere da questo articolo sono in PHP.

Creating the WordPress Post Views Counter Function in WPCode

Dopodiché, è possibile copiare e incollare il seguente codice:

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

A questo punto, basta scorrere la sezione “Inserimento” e selezionare “Inserimento automatico” per il metodo di inserimento e “Esegui ovunque” per la posizione. Questo funziona come inserire il codice nel file functions.php del vostro tema.

Successivamente, spostarsi nella parte superiore destra della pagina e rendere attivo il codice.

Quindi, fare clic su “Salva snippet”.

Choosing the insertion method and location in WPCode

A questo punto, è necessario aggiungere un altro snippet di codice personalizzato. Questo può essere chiamato ‘Track Post Views Function Call’.

Questo codice richiama la funzione di cui sopra e la attiva nelle pagine dei singoli post.

Una volta fatto, copiate e incollate il seguente snippet:

wpb_set_post_views(get_the_ID());

L’aspetto diverso di questo snippet di codice è che si sceglierà la posizione “Insert After Post” (Inserisci dopo il post), perché dovrebbe essere eseguito sulle pagine dei singoli post.

Choosing Insert After Post as the code insertion location in WPCode

Una volta terminato, basta rendere attivo il codice e salvarlo.

Inserire il gancio per il monitoraggio delle visualizzazioni dei post di WordPress

Ora è necessario aggiungere un nuovo frammento di codice che verifichi se la pagina corrente è un singolo post. In caso affermativo, chiamerà la funzione Contatore di visualizzazioni dei post di WordPress per tracciare e aggiornare il numero di visualizzazioni del post.

In questo modo, ogni volta che un utente visita il post, il suo numero di visualizzazioni viene aggiornato.

Chiamiamo questo snippet ‘WordPress Post Views Tracking Hook’. Quindi, inseriamo le seguenti righe di codice:

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

È possibile scegliere il metodo di inserimento come “Auto Insert” e la posizione come “Frontend Only”.

Come per i passaggi precedenti, basta attivare il codice e salvare lo snippet.

Choosing Frontend Only as the code insertion location in WPCode

Nota: se si utilizza un plugin per la cache, questa tecnica potrebbe non funzionare per impostazione predefinita. È possibile utilizzare la funzione di caching dei frammenti offerta da alcuni plugin di caching come W3 Total Cache per farla funzionare.

Aggiungere funzioni per recuperare il conteggio delle visualizzazioni dei post e visualizzare i post più popolari con il conteggio delle visualizzazioni

Siamo arrivati ai passi finali di questa guida. È necessario aggiungere uno snippet di codice che recuperi e formatti il numero di visualizzazioni di un determinato post di WordPress. Questo sarà utile in seguito quando si visualizzerà l’elenco dei post più visti.

È possibile denominare questo codice come ‘Funzione di recupero del conteggio delle visualizzazioni dei post’ e impostare la posizione su ‘Esegui ovunque’.

Ecco il frammento di codice:

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';
}

Anche in questo caso, assicuratevi di rendere attivo il codice in WPCode e di salvarlo successivamente.

Una volta fatto questo, create di nuovo un nuovo snippet di codice e chiamatelo “Visualizza i post più popolari con il conteggio delle visualizzazioni”. Questo è il codice che mostrerà i post più popolari in fondo ai post del blog.

Nella casella Anteprima codice, inserire il seguente snippet:

// 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(); 

Come indicato nel codice, è possibile regolare il numero di post da visualizzare e personalizzare il titolo di questa sezione.

Nella sezione WPCode Insertion, assicurarsi di selezionare ‘Insert After Post’ per la posizione. Quindi, rendere attivo il codice e salvare lo snippet.

Ora non resta che visitare uno dei post del blog e vedere se il codice funziona. Ecco come appare la sezione dei post più popolari per visualizzazioni sul nostro blog WordPress di prova:

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

Suggerimento dell’esperto: Per verificare se il codice funziona senza modificare in modo permanente il sito, si può provare la modalità di test di WPCode.

Questa funzione consente di aggiungere i codici come di consueto e di vedere solo l’aspetto del front-end. Dall’altra parte, gli utenti interagiranno con il vostro sito web come di consueto.

Speriamo che questo articolo vi abbia aiutato a capire come visualizzare i post più popolari in base alle visualizzazioni in WordPress. Potreste anche dare un’occhiata al nostro articolo su come visualizzare i prodotti popolari in WooCommerce e alla nostra guida per principianti sui campi personalizzati di WordPress.

Se questo articolo vi è piaciuto, iscrivetevi al nostro canale YouTube per le esercitazioni video su WordPress. Potete trovarci anche su Twitter e Facebook.

Divulgazione: I nostri contenuti sono sostenuti dai lettori. Ciò significa che se cliccate su alcuni dei nostri link, potremmo guadagnare una commissione. Vedi come WPBeginner è finanziato , perché è importante e come puoi sostenerci. Ecco il nostro processo editoriale .

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.

Il kit di strumenti WordPress definitivo

Ottenete l'accesso gratuito al nostro kit di strumenti - una raccolta di prodotti e risorse relative a WordPress che ogni professionista dovrebbe avere!

Reader Interactions

166 commentiLascia una risposta

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

    I think it would be easier to use a plugin maybe Monsterinsights or another as it straight forward than using custom code, but the issue is, I don’t think using Monsterinsights will shows view counts ??

    • WPBeginner Support says

      MonsterInsights would mot show the view count by default if that is what you want to include with your popular posts.

      Admin

  3. mohadese esmaeeli says

    The display of popular posts is beneficial as it helps increase website traffic statistics. However, on the other hand, competitors can easily identify which posts and topics have been popular on your site. One of the sections I always explore for competitor analysis and finding trending topics is the “most popular articles” section on various websites.

    • WPBeginner Support says

      While that can be something to keep in mind, we normally find it best to add what is most important to your visitors instead of being concerned that your competitors will follow your content.

      Admin

    • Mrteesurez says

      Yes, competitors can use it to analytics ones website but you can just display it like WPbeginner, without adding the views count/counter.
      But mind you, visitors can use Semrush, Google, Similarweb and some other ways to analyze your site. You own is just to know how you are playing your games.
      Thanks for the insight.

  4. Moinuddin Waheed says

    Popular posts and related posts makes the user engagement intact and reduced bounce rate.
    it helps in more user interaction with the posts and articles.
    I have seen many bloggers showing views count and read time of the posts, like 5 minutes read or 3 minutes read.
    can we have popular posts and related posts where ever we want with this method? and
    Is this method can be used for achieving both these objectives like having read time based on word counts?

    • WPBeginner Support says

      You should be able to place it wherever widgets are allowed. For the time to read, it would depend on the plugin you use for that and if it has an integration or not.

      Admin

  5. Jiří Vaněk says

    I would like to ask if the snippet also works on the new WordPress 6.4.2. I followed the instructions, cleared the cache, but the most read articles do not appear under the article

      • Jiří Vaněk says

        Thank you for the reply. It’s already working. I had a mistake somewhere and unfortunately I don’t know where. In the end, I repeated the whole procedure twice more and it worked on the third try. Unfortunately, I don’t know what I did wrong, but the snippets really work. Thank you.

        • WPBeginner Support says

          Glad they started working for you, it’s always difficult to tell what went wrong when trying the same code again works when the previous time it didn’t.

  6. Chris says

    If we have caching enabled, can we avoid the caching problem by resorting to JavaScript (AJAX) to send the command to record the view? Would that work?

    • WPBeginner Support says

      While there is a complex way to have that workaround, we do not have a method we would recommend at this time.

      Admin

  7. Amir says

    Hello, thank you very much.
    It is very simple and practical.

    But with each reload, one visit is added.
    How can I fix this problem?

    Thankful

    • WPBeginner Support says

      Any time a user would reload a page or visit the page again would be another visit. For specifically excluding refreshes you would need to use a plugin with more advanced features.

      Admin

    • WPBeginner Support says

      You may want to try clearing all caching checking with your theme’s support to ensure they don’t have anything that would conflict with this

      Admin

  8. za says

    Thank you for the tutorial. I applied it and it works. No need another plugin to show popular posts and the customized counter in single.

    Thanks!

  9. Chris says

    Is it beyond the scope of this article to explain had you assign the functions to those buttons as in your screenshot:

    Recent Articles – Popular Posts – editor’s picks

    That is basically what I want to do…have buttons at the top of my posts page for recent, popular/trending, editors picks. I haven’t found any plugins that can do that. The all focus on side bar widgets.

    It looks like your article is starting to talk about this but where to go from there is beyond my current knowledge level.

    Thanks,
    Chris

  10. Amit Biswas says

    Getting double view count on refresh (single.php). Don’t know if the remove action is working or not for “adjacent_posts_rel_link_wp_head”. Useless so far. I tried everything that is possible to remove double count. Using this code in a custom made plugin.

  11. Hans says

    Thsi thing works greats.

    Now I want the columnn in admin to be sortable. any idea how to do this?

    many thanks!

  12. Trevor says

    Hey, thanks for the code. Only issue I’m having is the view count is incrementing by 2 instead of 1 on refresh. Any thoughts?

    • Fuchel says

      This was happening for me because I had:

      `set_post_views(get_the_ID());` in single.php
      AND
      `add_action( ‘wp_head’, ‘track_post_views’);` in my functions.php which was also adding `set_post_views(get_the_ID());` within it.

      By removing the line on single.php I fixed the double count.

  13. Bülent Sakarya says

    Hello..

    Using w3total cache but count not working correctly.

    don’t use child theme. how can I fix it?

    thanks..

  14. Ryley Ameden says

    Fixed this issue:

    Cannot use WP_Query, used get_posts and it is now working. Then use a foreach look to loop through the posts and display them. See below:

    $blog_cat_array = get_the_category();
    $blog_cat = $blog_cat_array[0]->term_id;

    $popularpost = array(
    ‘posts_per_page’ => 2,
    ‘meta_key’ => ‘wpb_post_views_count’,
    ‘orderby’ => ‘meta_value_num’,
    ‘order’ => ‘DESC’,
    ‘category’ => $blog_cat,
    ‘post_type’ => ‘post’,
    );
    $pop_posts = get_posts($popularpost);

    foreach($pop_posts as $pop_post){
    the_title();
    }

  15. Erwin Barendregt says

    I really like this option and have built it into my site.
    I have one question regarding the count. I found that the counts were rather high so I changed the code around a bit. With every count increase I wrote the IP address to a log file. I found hat two-third of the counts were legit and the other ones came from googlebot, apple, etc. and just now apews Is there any way to get the counts right and do you know if the ‘regular’ plugins have found a way around this?
    Thx!
    BTW: Keep up the good work, I thoroughly enjoy this site!

    • bah says

      you can take maxmind ISP IP database and only count humans. This is the best option. Second just dont count common bots user-agent-names

      • Erwin Barendregt says

        Thanks so much. I will definitely look into that.
        In the mean time I implemneted the solution which was implemented in the WordPress Popular Posts plugin. That works for now, but the solution you recommended seems more future-proof. Thanks again!

  16. John says

    Hi! Awesome! This code helped me a lot!

    Do you know how to display the posts with 0 views? I have to enter to the post page by using the url the first time, otherwise it doesn’t show.

  17. Gianmarco says

    Awesome thanks this is really useful, but a question. Doesn’t it slow down the loading of the page significantly?

  18. ayaz says

    Hi,

    This is very useful post, i really appreciate. Can i filter the post in category, I wanted to show the post of specific category.

    Thanks.

  19. Bojan says

    Ok this is great. For some reason, post count doesnt show numbers, not sure is it because i work on a local., but what i wanted to ask even more, is how to add so it count only in the last 7 days?

  20. Dhiraj Kataria says

    I need advice on how r u to Load Word files to a WordPress website please. Is there an easy way?

  21. DarkSafka says

    Sadly this does not work with W3 Total Cache with Page Caching enabled. Coul not get any “fragmented caching” to work either.

  22. REIBI says

    Hey,
    This works great. But I need to show popular post of a day, this code shows popular posts of all time. Is there anyway to show popular posts of a day only.

    Any help will be greatly appreciated.

    Thanks :)

    • Dimitrios Arkolakis says

      Try to add something like this in the WP Query

      ‘date_query’ => array(
      array(
      ‘year’ => $today[‘year’],
      ‘month’ => $today[‘mon’],
      ‘day’ => $today[‘mday’],
      ),

      • Nick Heurter says

        This doesn’t seems to work. Is there anyone who figures out how to display the most popular posts of the lasts 7 days?

        Thanks!

  23. Mawardiy says

    Hi, I use Goodnews 5.7.2 theme, but where i put “wpb_get_post_views(get_the_ID());” in my theme, thank for u’r guidance

  24. Alex says

    Hey, thanks for the information.
    There’s a little problem. I put:

    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);
    }
    }
    //To keep the count accurate, lets get rid of prefetching
    remove_action( ‘wp_head’, ‘adjacent_posts_rel_link_wp_head’, 10, 0);

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

    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’;
    }

    and my visits counts always as two. What’s happening? Thanks.

    • ScoDal says

      I modified this a little to use it as a shortcode. To use this with a shortcode, add this to your functions.php:

      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);
      }
      }
      //To keep the count accurate, lets get rid of prefetching
      remove_action( ‘wp_head’, ‘adjacent_posts_rel_link_wp_head’, 10, 0);

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

      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’;
      }

      function wpb_most_viewed_posts() {
      // start output buffering
      ob_start();
      ?>
      4, ‘meta_key’ => ‘wpb_post_views_count’, ‘orderby’ => ‘meta_value_num’, ‘order’ => ‘DESC’);

      //begin loop
      while ($query->have_posts()) : $query->the_post(); ?>

      <?php

      // Turn off output buffering
      $theResult = ob_get_clean();

      //Return output
      return $theResult;
      }
      // Create shortcode
      add_shortcode('wpb_most_viewed', 'wpb_most_viewed_posts');

      //Enable shortcode execution in text widgets
      add_filter('widget_text', 'do_shortcode');

      Then simply add [wpb_most_viewed] to your desired page/post and it should display your most popular posts.

  25. John says

    Hello, great tutorial but I have one question.
    After following all of the steps the template isn’t paginating. It’s only showing the default 10 posts. Should this happen or is there a way to get it to paginate?

  26. Varange says

    Folks, please help. Just cannot figure it out.

    How do I change the args to the wp-query to show the most popular posts for the last week? Or month?

  27. Denis says

    Hello,
    can I do this with comments? I dont use any comments on my site so I could use this comment count to check my most popular page without adding a comment?
    Cheers,
    Denis

  28. Kes says

    I’ve found a number of tuts covering this topic but none seem to spell out where the line goes.

    I’ve tried it inside PHP tags and it breaks the page. If i place it in the HTML it just renders as a comment when you view source and no php is generated.

    Any ideas? I’m w3 total cache and my page views aren’t getting updated

  29. Jorge says

    Hello! How can I show the most popular posts for the current week?? Is there any possible? Thanks in advance.

Lascia una risposta

Grazie per aver scelto di lasciare un commento. Tenga presente che tutti i commenti sono moderati in base alle nostre politica dei commenti e il suo indirizzo e-mail NON sarà pubblicato. Si prega di NON utilizzare parole chiave nel campo del nome. Avremo una conversazione personale e significativa.