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. Hi, looking for query to remove posts without views, any ideas ? thanks 🙂

  2. Kevin, Thanks for this nice snippet.

  3. How will this work for a site with a very large traffic volume? I was looking into a post view plugin that is very popular (can’t remember the name of it now), and that was a concern mentioned in the comments.

  4. It works fine with new versions of WP. Make sure you have things setup correctly.

  5. Hi, there any way to reset the counter to zero views?

    1. Hi Cyndy everything is saved as meta data so you can just go into the post and change the value from whatever it is to zero.

      1. Kevin, thanks

        your tutorial very useful!!

        1. Hi Cyndy, Hi Kevin.
          Cool code.
          I can’t find the exact place where this meta data is stored for each post to change it.
          Inside the post (From Dashboard->Post->Edit) there is only the content of the post, no meta data.
          Thanks.

  6. Hi Kevin!
    I used your snippet for some time now and I’m happy, but in the last weeks something happened and it stopped counting all the views. I know this because i see 500 views from google analytics, yet the snippet shows only 18 views? I’m using the exact code you presented here, no modifications. I just changed a count last month and since then everything stopped working.

    1. Normally this would be because you have installed a new plugin or something along that lines. I have tested this snippet on new versions of wordpress and it should work just fine. Do you happen to have a cache plugin running on your site, like w3 total cache?

      1. I do have w3 installed. how is it affecting the snippet? it worked until now with it side by side, why is it causing problems now? I cleaned the cache many times and still nothing. ughhhh!

        1. because it would not be calling the setPost function since things are cached, send me an email using the contact form and ill send you and updated version that will solve the problem.

          1. can you share here?

  7. Is there any way for the views count to be reset every day in order to show just the number of views for the current day?

    1. Hi Pere,
      Yes absolutely, but you would have to change a fair amount of code to achieve this. Unfortunately not just a simple change,

      1. This is exactly what I am looking for. Is there any place where I can get this information?
        I need to implement a Trending Section Page for a customer of mine and I am a bit stuck with this at the moment. It seems I can’t get any information about it around the web.
        Any help would be very much appreciated!

    2. Hi Pere, did you find anything out about it?

  8. Mark Petherbridge janvier 10, 2015 à 8:25 pm

    Is there anyway to get this to only register unique views? Bashing f5 on my keyboard is cranking up the numbers.

    1. Hi Mark,
      Yes but not easily with this snippet. You could do some cookie checking, or tracking of ip addresses for better but not perfect unique views. Or even require users to be logged in and track on a users by user basis.

  9. $count = 0; in setPostViews() on line #15 should be removed, it doesn’t really do anything 😉

  10. Hands down the quickest snippet to implement
    I’m using it for several frontend notification methods, great work

    You rock!

  11. thank’s this tutorial

  12. Where is the count stored? Is it in a database?
    Wanted to know if it’s possible to change the values.

    Works well for me on latest version of wordpress, thanks.

  13. for me it is counting twice…

    1. Hi Andrew, is likely prefetching, or the setViews is added more than once. To solve the one issue try adding this. Note the code above.

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

  14. Hi, this seems to stop working in WP 4.0. Can anyone confirm or provide fix? thx u!

    1. Have you heard anything on this? I just upgraded to 4.0, and would like to use this.

    2. Same here.

    3. I’m using 4.0 and nothing wrong 🙂

  15. Wow. This saved me time. Very nice dude thank you.

  16. Great snippet but still incrementing on every post.

  17. Hello!
    Sorry for bad english, I’m using a translator. I’m from Brazil.
    I have a site that already has several views on the post, as I do not lose these views? Is to update the database? I use this plugin: WP-PostViews

  18. Would you happen to help me in styling the echo output. I want to put the views count on my loop and I accomplished that perfectly but how do I add a css to the output for the text? Any ideas on that. Thank You

    1. Hi Randy you can do the following by adding a div around the php function. i added a sample on pastebin
      http://pastebin.com/ThLasSJB

      1. I tried that right now and its not working.

      2. I tried that right now and its not working.

      3. I tried that right now and its not working.

      4. I tried that right now and its not working.

      5. I tried that right now and its not working.

      6. I tried that right now and its not working.

        1. Hi Randy,
          is the snippet displaying the number of views? if so it has something to do with your css or html as copying that snippet and placing it within your single post loop should work fine. You just have to define some styles to apply.

  19. Would you happen to help me in styling the echo output. I want to put the views count on my loop and I accomplished that perfectly but how do I add a css to the output for the text? Any ideas on that. Thank You

  20. Would you happen to help me in styling the echo output. I want to put the views count on my loop and I accomplished that perfectly but how do I add a css to the output for the text? Any ideas on that. Thank You

  21. Would you happen to help me in styling the echo output. I want to put the views count on my loop and I accomplished that perfectly but how do I add a css to the output for the text? Any ideas on that. Thank You

  22. Would you happen to help me in styling the echo output. I want to put the views count on my loop and I accomplished that perfectly but how do I add a css to the output for the text? Any ideas on that. Thank You

  23. Would you happen to help me in styling the echo output. I want to put the views count on my loop and I accomplished that perfectly but how do I add a css to the output for the text? Any ideas on that. Thank You

  24. Would you happen to help me in styling the echo output. I want to put the views count on my loop and I accomplished that perfectly but how do I add a css to the output for the text? Any ideas on that. Thank You

  25. Would you happen to help me in styling the echo output. I want to put the views count on my loop and I accomplished that perfectly but how do I add a css to the output for the text? Any ideas on that. Thank You

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 !