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.
Any idea of how to use this with a Custom Post Type?
awesome stuff exactly what I was looking for?
cool glad to hear you like the snippet enjoy.
Likewise can we count the number of images uploaded on the wordpress site, I am sure we can.. any clue?
Sorry for the delay!
http://wpsnipp.com/index.php/functions-php/count-total-number-of-jpg-gif-png-images-in-media-library/
Example of Bob is possible?
Most viewed posts
Post title3 100 views
Post title1 50views
Post title2 10 views
what is the impact of using this function over the WordPress database.. will I be able to clear of the logs (views) at set schedules.. ??
This is not a plugin with a lot of features simply this will increment the count in the post meta by one each time the post is viewed.
how to remove the “Views” word ?
Hi Joj,
You will see on line 09 return $count.’ Views’;
replace that line with the bellow and that is it.
return $count;
Thanks for the snippet. I slightly modified setPostViews() to discount post views from Editors or above:
function setPostViews($postID) {
if (!current_user_can('level_7') ) :
$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);
}
endif;
}
Thanks drew very cool.
Not working for me on localhost. Not sure why but every view, regardless if it’s an Editor level or above, gets counted.
On another note, how would you disable counting the view by the post’s author?
Oops. Wasn’t logged in as admin during testing. (facepalm)
Glad to hear you got things working.
Hey Kevin!
Tried this code out on a fresh WP 3.2 install and it works nicely. I however noticed that all though it should only increate the count by 1 mine does it by 4. Any suggestions what could be wrong?
Got the functions set up in the right place and the only change I did to it was to exclude counts from logged in visitors. Even without this change the code gives 4 views instead of 1.
Huh should only count by one, since its just count++ did you have any other people visit your site while it was running or multiple tabs open ?
Its on my localhost. Its really odd but might be just some browser thing. Thanks for a nice little snippet though!
Kevin,
First off, love the simplicity of this solution! I have the code working properly on my local server but noticed that when I reload my homepage (which contains my 5 most recent entries) each reload of my homepage ads a view to the count for each of the 5 posts. Is there any way to avoid that and only count the actual article page views? Thanks
Hi Rgsanchezz glad to hear you like the snippet. In regards to your question make sure you place setPostViews(get_the_ID()); within the single.php template or inside if(is_singular()) should also work if you don’t use a single.php template that should resolve the problem.
Did you use this snippet in a separate loop? If so, you should place the setPostViews(get_the_ID()); outside the “most viewed” loop so that it counts the +1 only for the currently displayed post and not everyone in the list. For Instance:
WRONG:
( ) CORRECT: ( )
Sorry, I copy-pasted the code into the reply box. Shortlinkoed via codepad, check it there : )
http://codepad.org/QOUWc3XB
Its Just a fake nothing else, dude If you are checking in firefox it will show but if you checked your url in chrome and IE its not displaying there. When you check in firefox it will show only your views nothing else…and if you think its my problem, just tell me.
Hi Sunnysuffy well the snippet is not fake, however if you have caching software running on your copy of wordpress it would have problems working. Supercache, etc.
[…] good example of the kind of tips you’ll find on wpsnipp.com is “Track post views without a plugin using post meta.” Kevin begins by describing what the snippet will accomplish, and then giving you a […]
hey, its cool..
thanks a lot.
Cool glad you like the snippet.
amazing, thank you!
no problem @4f9649a2dc0c5d186623a62544564bfe:disqus glad you like the snippet!
Needless to say, this is an awesome snippet. But if there is a solution to make it work with caching plugins, for instance with W3TC, it would be even better.
Anyway, good work!
I have not looked into this, ill take a closer look at some of the plugins and see what I can do. Glad you like the snippet though.
Hey Kevin, I’ve been browsing through forums to hit a solution. Apparently many people having problems with excluding functions from being cached. Unfortunately, there seems to be no cure any cure so far. I’m sure there is. Let’s hope one of us comes up with something soon 🙂
hello, As i know W3TC has a “Ignored query stems” to filter out some functions from cache.
hi nice information, is it possible to use echo getPostViews(get_the_ID()); in admin panel posts section if i want to use post views only for personal/admin purposes
Yes you can I posted a snippet not long after just for that reason.
http://wpsnipp.com/index.php/functions-php/display-post-views-within-admin-post-columns/
This is awesome, it works brilliantly. I will use it on a new wallpapers site I’m working on. Noted down your site on the functions for future reference.
I wonder if something can be done to only record only 1 view per session for every user. That would be cool to prevent “fake” views when refreshing the page. If anybody can do that (if it’s even possible) that would be awesome.
Thanks @6c9628c836d0d3ed67e8ef3b43a993dd:disqus Glad to hear you like the snippet! I’m sure something like that could be done, however I would use this as a method to track popularity of a post rather then for detailed stats.
I’m having an issue with this, if i view the second newest post the newest post get’s 1 view added, any ideas why?
The only reason I can think of is that you don’t have the setPostViews(get_the_ID()); function within the single.php? can you confirm this is the case…
Yeah it’s in the single.php in the loop
I am having the same problem after setting up a most popular posts list in the sidebar, using the “most Popular posts using views post meta” article. setPostViews(get_the_ID()); is in the single.php. setPostViews(get_the_ID()); is in the single.php.
I’m also having an issue here. Mine is in single.php, I followed the instructions. However I notice that if I visit a post (with a post ID let’s say 20), another post (with post ID let’s say 22) also gets +1 on views count. The weird thing is, when I echo the post ID received by the function setPostViews, only the post ID 20 is displaying on my screen.
Well it should work without any issues, however if you edit the posts you can see the custom field added with the current post views. I would reload the one page and see if the custom field updates on both posts. What version of wordpress are you currently running?
I was having the same issue. It took me forever to figure it out. The problem is caused by WordPress loading relational links for the previous and next posts in the head. Firefox, by default, prefetches REL links with the value of Next so both posts are being “viewed”
The solution I found was to remove the action that adds this functionality to the wp_head function: remove_action( ‘wp_head’, ‘adjacent_posts_rel_link_wp_head’, 10, 0);
Chris, thanks for the comment I updated the post to let others know about this fix for the issue. I also added a link to your site. Thanks again,
Hi Wprebel, You may have a plugin or something else that caused a problem with the snippet. The snippet is fairly simple and just updates the post meta when a user loads the post, not much to go wrong. Without looking at your theme in detail I would just be guessing,
@e4fcff6cc58dc5e1b2ab556d9cdb2cb2:disqus you need to use the getPostViews() function when you want to display post views and setPostViews() on the single.php.
[…] Track post views without a plugin using post meta […]
[…] Via : lien […]
This technique won’t work with cache plugin. I would like using WP-PostViews plugin as it provides a better compatibility with cache plugin.
This is true, it does not play nice with cache plugins. However as a quick snippet to track views it works quite well.
I would rename the post_views_count meta key to _post_views_count to make it hidden to avoid users editing the post views from custom fields.
Ahh good call Daniel, you could do that.
[…] you would like to display the number of views: <?php echo getPostViews(get_the_ID()); ?> Source →Track Post View Amount by Using Post MetaThis snippet will create a list of your most popular posts […]
Is there a way to make an overview of the most viewed posts?
Just like the populair in your sidebar, but with usage of the post view instead of the comments ?
Hi Alec,
I just finished a post for that yesterday and will be posting it in about an hour.
First time i visit your site, and already my hero! +1
Is it possible to make a list of mist viewed posts based on this code?
I’m not sure if I understand, can you go into a little more detail.
Example:
Most viewed posts
Post title3 100 views
Post title1 50views
Post title2 10 views
Hi Bob,
Yes I had thought about doing something like this, ill fool around with the idea for a bit and post a snippet.
Just found this post.
http://www.moocr.com/blog/posts/2010/display-posts-views-count-without-plugin-in-wordpress.html
Did what the guy said. Doesn’t seem to work. Does it work in localhost?
It should work on local host fine, however you would need to reload the page to see any views. Don’t forget to place setPostViews within the loop within single.php. I tested it on wpsnipp.com to track views and it worked fine. What the snippet does is add a number to post meta and then increment that each time the single.php loads. What version of wordpress are you running?
Thanks.Just found out that I wasn’t implementing it correctly.
Cool glad you got everything working perfectly…
Do I have to set them manually?:/
Yes you would need to add this code to your wordpress templates manually.
Awesome share Chad. Thanks 😀