X

Cómo realizar un seguimiento de las visitas a las entradas sin un plugin mediante Post Meta

Snippets by IsItWP

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

Comentarios   Deja una respuesta

  1. Opps sorry, please disregard my previous comment. I realized I was calling the setPostViews function multiple times. My bad….

    After fixing this, I am only seeing the view count go up +2 anytime I refresh the single blog post.

    Does anyone have a fix for this? I don’t imagine this will be much of a problem considering that most users wont actually be refreshing the page, though it would be nice to have an actual count number to display..

    Thanks for the code 🙂

  2. How to making a random views count to (600,900)

    please help..

  3. how do i stop auto increase count on page refresh?

  4. Hey, really great tips. Thanks for sharing with us. I am using plugin and google analytics to track my page views.

  5. Hi,

    I want to show the count inside meta class, my meta code is:

    how to print the counter between the meta like author, date, catagories?

  6. Risk Management Guru diciembre 1, 2016 en 2:24 pm

    Hi,

    Do you what is the standard PHP/wp field name for the post views? I only want to display that, simple.
    Thanks.

    Risk Manager

  7. try but don`t work for me.

  8. If I only need 5 I would have to change?

  9. Where will the post views appear?

    1. In the location you place the code within your template from step 2.
      echo getPostViews(get_the_ID()); you can put this within some html and style it if you wish. But the data is saved at post meta you should be able to see that when you edit a post within the custom fields section.

      1. w3t cache make fragment cache available just in pro version $$$

  10. Good afternoon,

    The snippet work great, but I need to reset the value.

    Could someone help me, please.

    I try this but doesn’t work – UPDATE wp_postmeta SET meta_value = ‘0’ WHERE wp_postmeta.meta_key =’post_views_count’

    Thank’s

    1. you can reset by going to your website database look for postmeta, click on it and search for post_view_count and delete all of them

      1. Sorry but i can’t find this field in my database, please explain how to reset counters to 0. Thx

        1. The post meta is found under the wp_postmeta table. If none of the rows in the meta_key column have post_views_count as the value, then it’s possible that the count has not been stored in the database yet.

  11. Hi guys, If someone look for count visits by ip adress, to count only one visit for each visitor this is the right code to do that, I hope is working fine to you, this is my modifications on “setPostViews” function :

    function setPostViews($postID) {
    session_start();
    $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{
    if(!isset($_SESSION[‘post_views_count-‘. $postID])){
    $_SESSION[‘post_views_count-‘. $postID]=”si”;
    $count++;
    update_post_meta($postID, $count_key, $count);
    }
    }
    }

    Just replace this function with old function and Well Done!!

    1. not working

      1. Lokendra Malviya octubre 16, 2017 en 1:04 am

        Thank you so much. The code is working for me:)

  12. Hey
    I am using it and it’s great But facing an annoying problem
    It counts twice in custom post type.

    Don’t know what to do to fix it any Help?

    1. Have you place the setPostViews() function within the single.php template or another template ?

      1. patrick1991groot agosto 27, 2016 en 6:28 am

        I have the exact same problem! Yes i placed it in only the single.php file… i use this icm wp car manager plugin… Also counting by 2 4 6 by every visit.

  13. This is a useful snippet. Thanks for sharing!

  14. Modifiqué la función y le agregué para que comprobace si había una sesión activa de la visita del póst y pues.. aca está;

    function wpb_set_post_views($postID) {
    session_start();
    $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{
    if(!isset($_SESSION[”post_views_count-‘. $postID])){
    $_SESSION[”post_views_count-‘. $postID]=”si”;
    $count++;
    update_post_meta($postID, $count_key, $count);
    }
    }
    }

    1. y para qué serviría eso? algo en especial?

  15. I’m getting double count each view. When viewed the post add two views instead of one.

    1. I have the same problem. Does anyone have any idea what’s the issue?

      1. what template file are you putting the setPostViews() function ?

        1. single.php
          I’ve tried putting setPostViews() both inside and ouside the loop, but couldn’t fix the issue.

          1. patrick1991groot agosto 27, 2016 en 6:29 am

            Also having the same issue…

          2. This works by calling the set views function adding post meta, so unless its called twice you would only get 1 view. I would check your theme to make sure nothing like multiple loops or anything is involved. However unless I was to see your themes single.php I could not be sure what the exact issue is.

        2. I’m having the same issue too. in the single.php either inside or outside the loop, it counts 2 every time I refresh the page…

          THis is my personal theme as well…

          I did notice however that I created a custom post theme template, keep it outside the loop just below the body tag, and it only counts once when i refresh the page…

          I also just tried putting it in the head of the header.php and it only counts once there as well…. the only time this doesn’t work right is when im looking at the domain.com/blog page and refresh it from there, the first post in the blog reel counts one time..

          oh well, I can deal with that… thanks again for the code…

          1. You may want to check if setPostViews(); is somehow being called twice, such as if the theme is somehow calling the template code twice.

  16. I can’t get this to work with W3 Total Cache. Is there any way it can work with it or is it absolutely impossible?

  17. Anybody else having issues getting the counter to work? I’m using WordPress 4.2 and have W3 Total Cache installed. The count remains at 0 no matter what (logged in user, logged out user, page refresh, cleared the cache).

    1. I’m only looking at getting the count to function via the backend. Any ideas would be greatly appreciated.

      1. me too!

        1. Did you solved this?. I think i can help you.

  18. fantastic, how do i get it to count post views only today
    thanks

  19. Works great in single.php, but how about in category.php. If you refresh the page all posts add one view, it should retrieve the real number of the post views.

    1. Have you figured this out yet? I’m using WP 5.2.2 and I’m getting +2 count on refresh… Other than that it looks like its working….

  20. works great, exactly what I wanted. thnx for sharing bro.

  21. Fernando Carrascosa mayo 15, 2015 en 4:53 am

    Hi!

    First of all, thanks for this script, it was very useful.

    I have a question, i have this snippet in a custom theme i’m developing in order to re-design/re-code my portfolio and i found that in custom-posts the counter is displayed, but when I’m in wp-admin it doesn’t show the number of visits i have as it does in regular posts.

    ¿Do you have any idea how to fix this?

    Thank you.

  22. Nice!! Thanks for the script!! Very Good!!

  23. this only counts my views how do i get it to count evert ones views

    1. Looking at the code in the post, it should definitely be tracking views for every visitor.

      You either have absolutely no visitors (This seems unlikely), or you put the setPostViews() function call inside a conditional block that only triggers if the user is either logged in or is a page admin

  24. Thanks for the script. Is there a way that we can display, for example, the 5 most viewed posts?

  25. Finally something simple and it works very good, thank u

Añadir un comentario

Nos alegra que haya decidido dejar un comentario. Tenga en cuenta que todos los comentarios se moderan de acuerdo con nuestra política de privacidad , y que todos los enlaces son nofollow. NO utilice palabras clave en el campo del nombre. Tengamos una conversación personal y significativa.

WordPress Launch Checklist

La lista definitiva para lanzar WordPress

Hemos recopilado todos los elementos esenciales de la lista de comprobación para el lanzamiento de su próximo sitio web de WordPress en un práctico ebook.
Sí, envíeme el ¡gratuito!