Display “Post Views Counter” in WordPress

I got this snippet of code to display my post views counter in my wordpress website.

    function bac_PostViews($post_ID) {

    $count_key = 'post_views_count';
    $count = get_post_meta($post_ID, $count_key, true);

    if($count == ''){
        $count = 0;
        delete_post_meta($post_ID, $count_key);
        add_post_meta($post_ID, $count_key, '0');
        return $count . ' Visitas';

    }else{
        $count++; 
        update_post_meta($post_ID, $count_key, $count);

        if($count == '1'){
        return $count . ' Visita';
        }
        else {
        return $count . ' Visitas';
        }
    }
}

Then, in my ‘single.php’ file I added this code for retrieving the count:

Read More
$blog_number_visits = bac_PostViews(get_the_ID());

And this code for showing the count:

if ( $blog_author || $blog_date || $show_comments_number ) {
        $meta .= '<p class="meta">';
        if ( $blog_date ) $meta .= esc_html( date_i18n( $date_format, strtotime( get_the_time( 'Y-m-d' ) ) ) ); 
        if ( $blog_date && $blog_author ) $meta .= ' &mdash; ';
        if ( $blog_author ) $meta .= '<span class="visitas">' . $blog_number_visits . ' </span>';
        if ( ( $blog_date || $blog_author ) && $show_comments_number ) $meta .= ' &mdash; ';
        if ( $show_comments_number ) $meta .= '<span class="commentCount"><a href="' . esc_url( $permalink ) . '#comments">' . $comments_number . '</a></span>';
        $meta .= '</p>';
    }

My problem is that I can’t display it in the home page. The HOME is getting the code from functions.php and if I put my snippet of code in functions.php and try to display it from there… It always shows 0 VIEWS.

I think maybe the problem is that functions.php is not inside ‘the LOOP’ and thats why is not displaying in the home.

My website: Website home where I want to display VIEWS COUNTER

Related posts

Leave a Reply