X

Como rastrear visualizações de posts sem um plug-in usando o Post Meta

Snippets by IsItWP

Está procurando uma maneira de rastrear as visualizações de posts sem um plug-in usando post meta? Embora provavelmente haja um plug-in para isso, criamos um trecho de código rápido que você pode usar para rastrear visualizações de posts sem um plug-in usando post meta no WordPress.

Instruções:

Adicione esse código ao arquivo functions.php do seu tema ou em um plug-in específico do site:

function getPostViews($postID){
    $count_key = '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 setPostViews($postID) {
    $count_key = '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);
    }
}

// Remove issues with prefetching adding extra views
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0); 

Opcionalmente, adicione esse código também a uma coluna no administrador do WordPress que exibe as visualizações de post:

// Add to a column in WP-Admin
add_filter('manage_posts_columns', 'posts_column_views');
add_action('manage_posts_custom_column', 'posts_custom_column_views',5,2);
function posts_column_views($defaults){
    $defaults['post_views'] = __('Views');
    return $defaults;
}
function posts_custom_column_views($column_name, $id){
	if($column_name === 'post_views'){
        echo getPostViews(get_the_ID());
    }
}

Essa parte do código de rastreamento de visualizações definirá as visualizações de posts. Basta colocar esse código abaixo no arquivo single.php dentro do Loop do WordPress.

<?php
          setPostViews(get_the_ID());
?>

Observação sobre o cache de fragmentos: Se você estiver usando um plug-in de cache como o W3 Total Cache, o método acima para definir visualizações não funcionará, pois a função setPostViews() nunca seria executada. No entanto, o W3 Total Cache tem um recurso chamado cache de fragmentos. Em vez do método acima, use o seguinte para que a função setPostViews() seja executada sem problemas e rastreie todas as visualizações de posts mesmo quando o cache estiver ativado.

<!-- mfunc setPostViews(get_the_ID()); --><!-- /mfunc -->

O código abaixo é opcional. Use esse código se quiser exibir o número de visualizações em suas postagens. Coloque esse código dentro do Loop.

<?php 
          echo getPostViews(get_the_ID());
?>

Observação: Se esta é a primeira vez que você adiciona trechos de código no WordPress, consulte nosso guia sobre como copiar/colar corretamente trechos de código no WordPress, para não danificar acidentalmente seu site.

Se você gostou desse snippet de código, considere dar uma olhada em nossos outros artigos no site, como: 10 melhores plug-ins de depoimento do WordPress e como configurar o rastreamento de autores no WordPress com o Google Analytics.

Comentários   Deixe uma resposta

  1. Hi,

    Can I do like fake views count + real count?

    It means I can set starting value manually (because I want my new published post to show a value like 3,429 views in the first minute) so that my post will look like it has a high amount of post views, of course, combined with real count also.

    If yes, where to set the fake view count base on the code?

  2. What would be the meta key for this to call it in a query?

    1. ‘post_views_count’ is the meta key.

  3. Hi is it possible to make somehow the number of views display only if it’s more than 1000?

    1. You could use this code when displaying the comment count:

      if (getPostViews(get_the_ID()) >= 1000) {
      echo getPostViews(get_the_ID());
      }

  4. Is there a way to exclude admin views from the count?

    1. You may want to use something like this code to conditionally count views: https://www.isitwp.com/check-if-user-is-logged-in/

  5. Hey Debjit Saha i can’t able to find single.php folder in my template, where should i paste the code?

    1. The main loop for single posts may be in another template file. You may want to check for a post.php file or a similarly named file.

  6. Thank you for this code. it worked perfectly.

  7. Nice snippet.
    How can I reset the counts and start counting again?

    1. If you know the post id of the posts you want then this should work.

      UPDATE yourDatabaseName.wp_postmeta
      set meta_value = 0
      where meta_key = ‘post_views_count’ and post_id = 1934

  8. Hello, very good your post.

    My question is how to bring the data from Google Analytics to show the number of views of Posts and Pages?

    Do you have a Post or a link on how to implement this?

    1. Sadly we don’t have a current recommendation for this exactly. That said, you may want to check out: https://www.monsterinsights.com/how-to-check-stats-for-individual-wordpress-posts-and-pages/

  9. Any google analytics plugin that can pull view data and display in wordpress?

    1. There are plenty… You can check out our complete list of best Google Analytics plugin.

  10. The codes are not working for me.I have bbpress topic,means post type is “topic”. But when i checked meta_key is genearting in backend. But meta values are not updating on each visits

  11. Great articles, it work fine on my page
    my question is, does the count will just start after implementing that code ?

    because all my old page showing 0 or 1 views while actually it already got thousands views.

    1. Yes, the counting doesn’t start until the plugin is active. Any views before this were not recorded by this plugin.

  12. Thanks a lot – works great!

    I’ve ‘improved’ the function get_post_views slightly so it will return the proper text depending on the number of views. Here is my version:

    function get_post_views($postID) {
    $count_key = ‘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 Views”;
    }
    if ($count==’1′) {
    return “1 View”;
    }
    return $count.’ Views’;
    }

    Maybe you like to adopt this version.

    1. Thanks for sharing! 🙂

  13. thanks.

  14. This has helped me a lot, thank you very much!

  15. Great! Works like charm… I only wanted to view it in the admin area and just the first two codes do the trick!

  16. Hi,

    Thanks for the code, it works like a charm without cache enabled…

    But, how can I make it work with wp rocket?

    Please…

  17. Anyone know how to format or truncate the numbers? So instead of 4445 views, it’s 4,445 or 4.5K ?

    1. You may want to use PHP functions like round() and number_format() for this use case.

  18. Hi, somehow my code runs fine but it is doing +2 increment each time, the views go 0, 2, 4, 6. Which has been annoying please help. I placed the code as well as the show post views portion both in a function that has a action after content. The counter works, just that its in multiples of 2.

    1. You may want to check to make sure that this function, setPostViews(get_the_ID()), is only added once. Which hook are you using?

  19. wil the work in lightspeed cache?

  20. Military_blogger junho 30, 2019 em 6:17 am

    Code appearing on home page

  21. Opps sorry, please disregard my previous comment. I realized I was calling the setPostViews function multiple times. My bad….

    After fixing this, I am only seeing the view count go up +2 anytime I refresh the single blog post.

    Does anyone have a fix for this? I don’t imagine this will be much of a problem considering that most users wont actually be refreshing the page, though it would be nice to have an actual count number to display..

    Thanks for the code 🙂

  22. How to making a random views count to (600,900)

    please help..

  23. how do i stop auto increase count on page refresh?

  24. Hey, really great tips. Thanks for sharing with us. I am using plugin and google analytics to track my page views.

  25. Hi,

    I want to show the count inside meta class, my meta code is:

    how to print the counter between the meta like author, date, catagories?

Adicionar um comentário

Ficamos felizes por você ter optado por deixar um comentário. Lembre-se de que todos os comentários são moderados de acordo com nossa política de privacidade, e todos os links são nofollow. NÃO use palavras-chave no campo do nome. Vamos ter uma conversa pessoal e significativa.

WordPress Launch Checklist

A lista de verificação definitiva para o lançamento do WordPress

Compilamos todos os itens essenciais da lista de verificação para o lançamento de seu próximo site WordPress em um ebook prático.
Sim, envie-me o livro eletrônico gratuito grátis!