X

Comment suivre les vues d’un article sans plugin en utilisant Post Meta

Snippets by IsItWP

Vous cherchez un moyen de suivre les affichages des articles sans plugin en utilisant post meta ? Bien qu’il y ait probablement un plugin pour cela, nous avons créé un extrait de code rapide que vous pouvez utiliser pour suivre les vues des articles sans plugin en utilisant post meta dans WordPress.

Instructions:

Ajoutez ce code au fichier functions.php de votre thème ou dans un plugin spécifique à votre 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); 

Vous pouvez également ajouter ce code à une colonne de l’administration de WordPress qui affiche les vues des articles :

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

Cette partie du code de suivi des vues définira les vues de l’article. Il suffit de placer ce code ci-dessous dans le fichier single.php à l’intérieur de la boucle WordPress.

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

Note sur la mise en cache des fragments : Si vous utilisez un plugin de mise en cache comme W3 Total Cache, la méthode ci-dessus pour définir les vues ne fonctionnera pas car la fonction setPostViews() ne s’exécutera jamais. Cependant, W3 Total Cache dispose d’une fonctionnalité appelée mise en cache des fragments. Au lieu de la méthode ci-dessus, utilisez la suivante pour que la fonction setPostViews() s’exécute parfaitement et suive toutes les vues de vos messages, même lorsque la mise en cache est activée.

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

Le code ci-dessous est optionnel. Utilisez ce code si vous souhaitez afficher le nombre de vues dans vos articles. Placez ce code dans la boucle.

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

Note : Si c’est la première fois que vous ajoutez des extraits de code dans WordPress, veuillez consulter notre guide sur la façon de copier/coller correctement des extraits de code dans WordPress, afin de ne pas casser accidentellement votre site.

Si vous avez aimé cet extrait de code, n’hésitez pas à consulter nos autres articles sur le site comme : 10 meilleurs plugins WordPress de témoignages et comment configurer le suivi des auteurs sur WordPress avec Google Analytics.

Commentaires   laisser une réponse

  1. Hàng xách tay avril 6, 2013 à 2:45 am

    thanks

  2. I added the remove_action() , but still it adds 1 count to the recent post when i open any of the post. Please help .

  3. Hey thanks man! But i dont get the image with views as you show here. Can you help me on this to get the image also.

  4. Tam Nguyen Photography février 1, 2013 à 11:13 pm

    I’ve found that this code snippet doesn’t match with what I see with my Jetpack stats. Anybody else having the same problem?

  5. it counts only unique views, how to change it to counts every single view (every refresh)

  6. Awesome tips ! Thanks a lot.

  7. Awesome tips ! Thanks for sharing. I’d need a little more help though.
    I would like to display the most popular posts for only the last week or month ? Anybody can help ? Thx

  8. Great snippet. Works awesome.

    Do you know if it is possible to now have a “Most Popular Categories” list, based on the categories of the most viewed posts?

  9. I have tried this code it is inserting count but displaying same count for all post even I have added

    remove_action( ‘wp_head’, ‘adjacent_posts_rel_link_wp_head’, 10, 0);
    Any idea?

  10. This looks like it works but I see an issue in my particular case…I am using this code within a sidebar widget (adding read count to a latest posts query):

    $args = array( ‘numberposts’ => 3, ‘order’=> ‘ASC’, ‘orderby’ => ‘title’ );
    $postslist = get_posts( $args );
    foreach ($postslist as $post) : setup_postdata($post);
    setPostViews(get_the_ID()); ?>

    I see two things:

    – The three posts listed always show an incremental count compared to one another (post 1 = 0 views, 2 = 1 view, 3 = 2 views). I’m not sure that is accurate.
    – When I refresh the page, these all have 3 added to the count (0, 1, and 2 now show 3, 4 and 5). I did add the remove_action code to functions.php but it looks like it had no effect.

    Not sure what could be the cause for this….

  11. when i create a new tab in firefox, and it increments by 1, but i refresh the page, it increments by 2.
    Anyone has the same problem? why it happens? becauseof browser?

  12. Justin W Hall mai 31, 2012 à 11:53 pm

    hmmmmmm, how can I decrease by one after, say 24 hours ir incrementing?

    1. Let me just see if I understand correctly you want to minus one from each view every 24 hours ?

      1. Yep, for each hit, subtract a hit 24 hours later. Get it? Ended up using a cron job. If you have an easier solution. I’m all ears.

        1. a cron is about the best way, another way would rely on people viewing a page to decrement and could easily get way behind.

  13. WordPress Users: How to Increase Functionality AND Speed Up Your Site - ManageWP mai 31, 2012 à 11:00 am

    […] Track post views using post meta […]

  14. thank you man for your work.. it’s great

  15. awesome work
    can i get code 
    to show the most viewed posts in widget or page 
     

  16. Kevin,
    Can this script be used for custom post types?

    1.  Hi Rafa, should be able to use this without any problems.

    2.  Ok, I will give it a shot.  How do we get the view counts to display on the CPT admin post columns?

      Thanks!

      1. Figured out my issue, I had to add “post_type=any” to the query and I now see all my custom post types.

  17. Awesome! Thanks for the code, seems to be working great.

  18. Bhaskar Relan mars 9, 2012 à 6:27 pm

    Thanks a lot dear…A great piece of work….

    1. Bhaskar Relan mars 10, 2012 à 6:32 am

       Yesterday I said it works…but somehow when we click on post it calculates fine but when we go to second newest post and then go to newest post the count for newest post is incremented by 2. Similar pattern can be seen with three.

      In case of three posts if we go to third newest post it will be incremented by 1 but when we go to second newest post it gets incremented by 2 and then go to newest post it is also incremented by 2.

      It we great if anyone can help on this issue.

      1. me too, every post is incremented by 2. why???

  19. it works on chrome, firefox, but in safari, when refresh page the view number increase by 2, it there a fix, does anyone tested on safari

    1. find the problem, a line of jquery code makes it count twice when refresh, no idea why, but fixed it.

      1. Hello, I have the same problem. Can you help me how did u fix it please? For me it counts twice in all of browsers

  20. Hi everybody !!

    Great tips ! Thank you very much.

    I was wondering if we can add a “time” data ?
    Because I would like to show the view of yesterday/ 2 days ago / 2 days ago etc… ?

    1. wp_get_archives lets you define a short time period something like this I think would be useful.
       
      http://codex.wordpress.org/Function_Reference/wp_get_archives

      1. Ok I know what you mean but this is not exactly what I want.
        I would like to make a kind of graph.
        To make a function which show if the post has positive or negative views. So I want to compare the view from yesterday and from today.

        1. Well that is much more complex, I would suggest something more simple grab a plugin like this.

          http://wordpress.org/extend/plugins/official-statcounter-plugin-for-wordpress/

  21. Hi Kevin – Great stuff 😉 Quick question: Its works smooth for me but the counting starts from 0. Is possible to retrieve the views that I already had on the posts? thx

    1.  Hi Hugo,
      Well the snippet saves to post meta, so if you had removed the snippet then added it again should continue from last values. However you can always edit the custom fields to change the values.

  22. Hello 
    Kevin Chard , i come from Viet Nam, my english is not good 🙁
    I want to ask you one question 🙂 : how to display post view for only admin (only admin can see the post view ) 😀
    You can send the code via my email 😀

    1.  this snippet will display the post views within the post column within the admin. However if you want to display within the site but only for admins you can just do this.

      if(is_admin()){
            echo getPostViews(get_the_ID());
      }

      1. Kevin how can I configure it so that it only counts visitors who aren’t admin? This is not a display issue but a counting one. Im sure !is_admin() comes into it but not sure where? Thanks for great snippets btw.

        1. This should work for you, just replace step one code with the following.
           
          if(!current_user_can(‘administrator’)){
                echo setPostViews(get_the_ID());
          }

  23. How can we display the post views only in the admin page where all posts are displayed. I mean the edit.php page

  24. how to remove the  “Views” word ?

    1. Christopher McMahon janvier 8, 2012 à 10:48 am

      Edit Line 9

  25. Thanks, I am using it on a NEW site and it is working brilliantly….

    I am learning PHP on the GO, so your code taught me a couple of things.. THANKS AGAIN…

    1. Cool Zaid, glad to hear you like the site and hope that you enjoy the snippets!

Ajouter un commentaire

Nous sommes heureux que vous ayez choisi de laisser un commentaire. N'oubliez pas que tous les commentaires sont modérés conformément à notre privacy policy, et que tous les liens sont en nofollow. N'utilisez PAS de mots-clés dans le champ du nom. Engageons une conversation personnelle et constructive.

WordPress Launch Checklist

L'ultime liste de contrôle pour le lancement de WordPress

Nous avons rassemblé tous les éléments essentiels de la liste de contrôle pour le lancement de votre prochain site Web WordPress dans un ebook pratique.
Oui, envoyez-moi le gratuit !