Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Display WordPress posts by number of Views

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 404
    Comment on it

    Displaying the most viewed posts becomes very helpful for every user to have a look at trendy blog post in your WordPress.

    There are so many plugins that will help us easily to add most viewed/poipular posts in our WordPress website. But there is an easy way we can add popular posts by adding few lines of code.

    We can use post meta for storing the number of  post views count. Using the stored Meta value, we will fetch the posts according to the post visits/views.

    For doing this, we only have to add few lines of code in WordPress theme's function.php and single.php file.

    In function.php you can add the following code.

    function setPostViews($postID) {
        $countKey = 'post_views_count';
        $count = get_post_meta($postID, $countKey, true);
        if($count==''){
            $count = 0;
            delete_post_meta($postID, $countKey);
            add_post_meta($postID, $countKey, '0');
        }else{
            $count++;
            update_post_meta($postID, $countKey, $count);
        }
    }

    In single.php , just copy this 1 line of code .Single.php file in WordPress is the file for displaying WordPress blog posts

     

    setPostViews(get_the_ID());

    After adding these lines of code, you can display popular wordpress post in any place in your WordPress blog by adding few lines of code for display.

     

    You can add this code anywhere in your pages,where you want to display the posts.

     

    <?php
    query_posts('meta_key=post_views_count&orderby=meta_value_num&order=DESC');
    if (have_posts()) : while (have_posts()) : the_post();
    ?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php
    endwhile; endif;
    wp_reset_query();
    ?>

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: