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

  2. 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

  3. 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

  4. 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

  5. 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

  6. 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

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

  8. Md. Iftekharul Ibna Alam avril 17, 2014 à 1:59 am

    Its conflict with w3 total cache, counts are increasing automatically in my blog. If anyone visits any of my post, the counts of rest of the posts are also increasing. Is there any solutions for this type of confliction?

    1. If you look at the first snippet at the bottom we have the following as

      prefetching with some browsers can add views to posts not viewed.

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

      The other thing to keep in mind that this snippet is not setup to play nice with cache plugins
      So I can’t be sure within much more testing how well this will work.

    2. If you look at the first snippet at the bottom we have the following as

      prefetching with some browsers can add views to posts not viewed.

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

      The other thing to keep in mind that this snippet is not setup to play nice with cache plugins
      So I can’t be sure within much more testing how well this will work.

    3. If you look at the first snippet at the bottom we have the following as

      prefetching with some browsers can add views to posts not viewed.

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

      The other thing to keep in mind that this snippet is not setup to play nice with cache plugins
      So I can’t be sure within much more testing how well this will work.

  9. Yves Jeanrenaud avril 1, 2014 à 4:44 pm

    thanks for the code. I updated it to also work with caching and not using wordpress functions but directly altering the post_meta table. is anyone interested in these updates?

    1. Hi Yves Jeanrenaud I think many people on wpsnipp would love it. If you send the snippet along with some details, domain etc. That way we can give you credit that would be great.

      http://wpsnipp.com/index.php/contribute/

      1. Yves Jeanrenaud avril 7, 2014 à 5:25 pm

        ok, will do 🙂

    2. Hector Castilla avril 16, 2014 à 11:07 pm

      hi Yves, can you share your code? this snippet seem don’t work ok, as Tam ‘Heisenberg’ Nguyen said, my statistics don’t match too.

    3. Hector Castilla avril 16, 2014 à 11:07 pm

      hi Yves, can you share your code? this snippet seem don’t work ok, as Tam ‘Heisenberg’ Nguyen said, my statistics don’t match too.

    4. Hector Castilla avril 16, 2014 à 11:07 pm

      hi Yves, can you share your code? this snippet seem don’t work ok, as Tam ‘Heisenberg’ Nguyen said, my statistics don’t match too.

    5. Hi can you pls share the code here. I use WP Super Cache and i have problem with the counter.

      1. Yves Jeanrenaud août 9, 2014 à 4:49 pm

        I did

        1. Hi Yves,
          I don’t think I ever got the code from you, send me an email on contribute and ill contact you via gmail so you can send it again if you don’t mind I think the code may have been the problem when sending it via the email form.

          1. Yves Jeanrenaud août 14, 2014 à 4:18 pm

            oh really? my bad. I’ll send it again.

  10. Abdulrahman Hariri mars 26, 2014 à 7:18 pm

    Excellent code, thanks Kevin. I was wondering if you have tried to use this in author profiles? I am thinking of trying to use another version of this code to store values into author’s meta and count their profile page visits.

    Thanks!

    1. Hi Abdulrahman Hariri,
      No I have not tried this in the author profiles myself however I can’t see any reason why it would not work. Other than updating the user meta rather than post meta should work well.

      1. Abdulrahman Hariri mai 31, 2014 à 11:07 am

        I’ve tried it and its working :). Thanks a lot for the information!

  11. Abdulrahman Hariri mars 26, 2014 à 7:18 pm

    Excellent code, thanks Kevin. I was wondering if you have tried to use this in author profiles? I am thinking of trying to use another version of this code to store values into author’s meta and count their profile page visits.

    Thanks!

  12. Is it possible to get the profile viewers count with this code?

  13. Is it possible to get the profile viewers count with this code?

  14. WordPress Users: How to Increase Functionality AND Speed Up Your Site janvier 30, 2014 à 10:19 am

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

  15. Is it possible to change the ‘trigger’ of increment? for example, make certain links inside the post to increase the post-meta value whenever it’s being clicked. With this, maybe we can use this cool snippet for other uses. (ex: how many times our download link has been clicked)

  16. Friend how to do it also work on top the most visited post with this code below in your scripts ?

  17. If I have a custom field called views and exceeds 100 views, how I can show certain message in a template?

  18. This is perfect. Exactly what I was looking for.

  19. Md. Iftekharul Ibna Alam juillet 16, 2013 à 4:56 pm

    You ordered the code snippet very nicely, and easy to understand. Now, I have posts view count in my blog. Thanks

  20. Great this works perfectly!

  21. This awesome thank a million

  22. good to know ,3q….

  23. tanks

  24. Thanks for the great snippet Man. is there anyway to accumulate all the previous visits to my every single post with the current post view count?

  25. Is it possible to reset this counter? So lets say I want to display my most “popular posts of the week”. Every week the post views resets to 0.

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 !