¿Estás buscando una manera de rastrear las visitas a las entradas sin un plugin usando post meta? Si bien es probable que haya un plugin para esto, hemos creado un fragmento de código rápido que se puede utilizar para realizar un seguimiento de vistas de post sin un plugin usando post meta en WordPress.
Instrucciones:
Añade este código al archivo functions.php de tu tema o en un plugin específico del sitio:
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, añada también este código a una columna del administrador de WordPress que muestre las vistas de las entradas:
// 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()); } }
Esta parte del código de seguimiento de vistas establecerá las vistas de la entrada. Sólo tiene que colocar este código a continuación dentro del archivo single.php dentro del bucle de WordPress.
<?php setPostViews(get_the_ID()); ?>
Nota sobre el almacenamiento en caché de fragmentos: Si está utilizando un plugin de almacenamiento en caché como W3 Total Cache, el método anterior para establecer vistas no funcionará, ya que la función setPostViews()
nunca se ejecutaría. Sin embargo, W3 Total Cache tiene una función llamada fragment caching. En lugar del método anterior, utilice el siguiente para que la función set
PostViews() se ejecute correctamente y rastree todas las vistas de sus entradas incluso cuando tenga habilitado el almacenamiento en caché.
<!-- mfunc setPostViews(get_the_ID()); --><!-- /mfunc -->
El siguiente código es opcional. Utilice este código si desea mostrar el número de visitas dentro de sus mensajes. Coloque este código dentro del Bucle.
<?php echo getPostViews(get_the_ID()); ?>
Nota: Si es la primera vez que añade fragmentos de código en WordPress, consulte nuestra guía sobre cómo copiar / pegar correctamente fragmentos de código en WordPress, para no romper accidentalmente su sitio.
Si te ha gustado este fragmento de código, por favor considere revisar nuestros otros artículos en el sitio como: 10 mejores plugins de testimonios para WordPress y cómo configurar el seguimiento de autores en WordPress con Google Analytics.
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
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
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
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
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
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
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
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?
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.
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.
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.
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?
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/
ok, will do 🙂
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.
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.
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.
Hi can you pls share the code here. I use WP Super Cache and i have problem with the counter.
I did
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.
oh really? my bad. I’ll send it again.
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!
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.
I’ve tried it and its working :). Thanks a lot for the information!
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!
Is it possible to get the profile viewers count with this code?
Is it possible to get the profile viewers count with this code?
[…] Track post views using post meta […]
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)
Friend how to do it also work on top the most visited post with this code below in your scripts ?
If I have a custom field called views and exceeds 100 views, how I can show certain message in a template?
This is perfect. Exactly what I was looking for.
You ordered the code snippet very nicely, and easy to understand. Now, I have posts view count in my blog. Thanks
Great this works perfectly!
This awesome thank a million
good to know ,3q….
tanks
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?
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.