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.
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?
What would be the meta key for this to call it in a query?
‘post_views_count’ is the meta key.
Hi is it possible to make somehow the number of views display only if it’s more than 1000?
You could use this code when displaying the comment count:
if (getPostViews(get_the_ID()) >= 1000) {
echo getPostViews(get_the_ID());
}
Is there a way to exclude admin views from the count?
You may want to use something like this code to conditionally count views: https://www.isitwp.com/check-if-user-is-logged-in/
Hey Debjit Saha i can’t able to find single.php folder in my template, where should i paste the code?
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.
Thank you for this code. it worked perfectly.
Nice snippet.
How can I reset the counts and start counting again?
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
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?
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/
Any google analytics plugin that can pull view data and display in wordpress?
There are plenty… You can check out our complete list of best Google Analytics plugin.
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
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.
Yes, the counting doesn’t start until the plugin is active. Any views before this were not recorded by this plugin.
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.
Thanks for sharing! 🙂
thanks.
This has helped me a lot, thank you very much!
Great! Works like charm… I only wanted to view it in the admin area and just the first two codes do the trick!
Hi,
Thanks for the code, it works like a charm without cache enabled…
But, how can I make it work with wp rocket?
Please…
Anyone know how to format or truncate the numbers? So instead of 4445 views, it’s 4,445 or 4.5K ?
You may want to use PHP functions like round() and number_format() for this use case.
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.
You may want to check to make sure that this function, setPostViews(get_the_ID()), is only added once. Which hook are you using?
wil the work in lightspeed cache?
Code appearing on home page