How To Display Most Viewed Posts in WordPress Without a Plugin

Do you want to show your Most Viewed Posts on your Blog? In this tutorial, I will show you how to display your most popular posts (based on Views) in WordPress Without a Plugin. Probably you already have seen Blogs displaying the Most Viewed Posts and you wonder how it is done.

This tutorial is a natural progression from my previous tutorial: How To Track & Display Post Views Count in WordPress Without a Plugin. Now after we tracked the most popular posts by number of views, it is time to display them on the Blog.

What About a Plugin?

Yes, there are plugins that display the most popular posts on your blog, but they all tend to do a lot more than you need. Also I encourage you to read my previous post about unnecessarily adding plugins to your theme. Personally, I am not a fan of plugins, I prefer to use code snippets rather than using Plugins. Also, aren´t you eager to learn?

Final Result

The 2 images below show an example of the Most Viewed Posts displayed at the top right sidebar of this blog, for 2 of the 4 themes I have available. The numbers between parenthesis represent how many times the post have been viewed so far.

Diary theme: Most Viewed Posts.

Emplode theme: Most Viewed Posts.

Prerequisite

To display Most Viewed Posts in your Blog, you need to add the view counter for every post. In other words, you need to add to your theme: (CODE-1 and CODE-2 and CODE-3) or (CODE-1 and CODE-2a and CODE-3) from my previous tutorial. Implementing my previous tutorial is a must.

If you want to show Most Viewed Posts, but you don´t want to show the Post Views Column in your admin area (dashboard), then you can remove CODE-3 with the exception of the get_PostViews() function (line 12 to 19 of CODE-3), in addition to CODE-1 and CODE-2, of my previous tutorial.

Display Most Viewed Posts | sidebar.php

Open the sidebar.php file located in your theme´s folder, and add (copy and paste) the following CODE-4 where you want your Most Viewed Posts list to appear. Save the file and upload it to the server.

CODE-4 :: Displays Most Viewed Posts

Note: To scroll within the code: You can also click on the code window and use your keyboard´s arrow keys.

<!-- 
********************************* CODE-4 ************************************
* @Author: Boutros AbiChedid 
* @Date:   January 22, 2012
* @Websites: http://bacsoftwareconsulting.com/ ; http://blueoliveonline.com/
* @Description: Displays the MOST VIEWED POSTS in the sidebar of Your Blog.
* @Tested on: WordPress version 3.2.1 
-->
<div class="box">
<div class="box_title">Most Viewed Posts</div> 
<div class="box_content">
<ul>
<?php
    query_posts('meta_key=post_views_count&orderby=meta_value_num&posts_per_page=5');
    //If there are posts. checks to see if the current query has any results to loop over. 
    if (have_posts()) :
        //loop through the posts and list each until done. 
        while (have_posts()) : 
			//Iterate the post index in The Loop. 
			the_post(); 
			?>
        	<li><a href="<?php the_permalink() ?>" title="Permanent Link to: <?php the_title_attribute(); ?>"><?php the_title(); ?></a> <?php echo '(' . get_PostViews(get_the_ID()) .')'; ?></li>      
    <?php
    	endwhile; 
	endif;
    //Destroy the previous query. This is a MUST.
    wp_reset_query();
	?> 
</ul>
</div> 
</div><!-- END OF MOST VIEWED POSTS. -->    

CODE-4 Notes:

The most important part of the code are lines 13 to 28, these Lines should not be modified. The HTML tags can be changed or removed depending on your theme. Also CSS classes should be modified to fit your theme´s style.

On line 14 of the code: I set the posts_per_page parameter to 5, meaning that the five Most Viewed posts will be displayed. You can change this number to whatever you like. Also, if you totally removed posts_per_page parameter (if you removed &posts_per_page=5), then the Most displayed posts will default to whatever number you set it in your dashboard (Administration > Settings > Reading).

This code requires (CODE-1 AND CODE-2 AND CODE-3) or (CODE-1 AND CODE-2a AND CODE-3) of my previous tutorial.

If you want to show Most Viewed Posts, but you don´t want to show the Post Views Column in your admin area (dashboard), then you can remove CODE-3 with the exception of get_PostViews() function, (line 12 to 19 of CODE-3) of my previous tutorial.

Some themes have more variations of the sidebar.php file, so look at their documentation and see where best to add the code. For instance, for the “Clear Line” theme I added the code in “layouts/right-sidebar.php” file.

If your theme is not widegetized, then you can add the code anywhere you like in the sidebar. However, if your theme is widget ready, meaning that your theme supports a dynamic sidebar, then there is a limitation to where you can place the code. In this case, the code is placed at the top before the start of your dynamic widgets.

Even though I talk about placing the code in the sidebar. However; you can add the code anywhere you like on your WordPress Blog (left, right, header, footer).

CODE-4 works on WordPress 2.3.0 and newer. But I hope that you will upgrade to the latest version.

Note: If you don´t see the horizontal bar, and to scroll within the code, you can also click on the code window and use your keyboard´s arrow keys.

1. If you want to display Most Viewed Posts For a Specific Category, then replace line 14 of CODE-4 with the following line: (Note that the number 76 is one of the category IDs on this blog, you need to replace this number with yours.)

query_posts('meta_key=post_views_count&orderby=meta_value_num&posts_per_page=5&cat=76');

2. If you want to display Most Viewed Posts for multiple Categories, then replace line 14 of CODE-4 with the following line: Note that the number 76 and 40, are separated by commas, and are 2 of the category IDs on this blog, you need to replace these 2 numbers with yours.

query_posts('meta_key=post_views_count&orderby=meta_value_num&posts_per_page=5&cat=76,40');

3. If you want to display Most Viewed Posts For a Specific Year (let´s say 2011), then replace line 14 of CODE-4 with the following:

query_posts('meta_key=post_views_count&orderby=meta_value_num&posts_per_page=5&year=2011');

The Category IDs, specified above, are different in your case. If you don´t know how to find the category ID, read my previous tutorial on How To Find the Category ID.

Hopefully you got the idea how you can manipulate the query_posts() function for your specific needs.

CODE-4 References:

Real Example(1) | Where to Add CODE-4 | Emplode Theme

This is where I added CODE-4 for the “Emplode Theme” of this Blog (in the sidebar.php file).

</div>
</div>

<div class="right" id="sidebar">
<div id="sidebar_content">

<!-- part of the sidebar.php code removed for brevity. --> 

<!-- MOST VIEWED POSTS Code by BOUTROS ABICHEDID (placed above the start of the widgets) -->
<div class="box">
<div class="box_title">Most Viewed Posts</div> 
<div class="box_content">
<ul>
<?php
    query_posts('meta_key=post_views_count&orderby=meta_value_num&posts_per_page=5');
    //If there are posts. checks to see if the current query has any results to loop over. 
    if (have_posts()) :
        //loop through the posts and list each until done. 
        while (have_posts()) : 
			//Iterate the post index in The Loop. 
			the_post(); 
			?>
        	<li><a href="<?php the_permalink() ?>" title="Permanent Link to: <?php the_title_attribute(); ?>"><?php the_title(); ?></a> <?php echo '(' . get_PostViews(get_the_ID()) .')'; ?></li>      
    <?php
    	endwhile; 
	endif;
    //Destroy the previous query. This is a MUST.
    wp_reset_query();
	?> 
</ul>
</div> 
</div><!-- END OF MOST VIEWED POSTS. -->    

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar() ) : ?>

<?php the_subpages(); ?>

<?php if ( $recent_posts = get_posts('numberposts=10') ) : ?>

<div class="box">
	
	<div class="box_title">Recent posts</div>

	<div class="box_content">
		<ul>
	<?php foreach ( $recent_posts as $post ) : setup_postdata($post); ?>
			<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
	<?php endforeach; ?>								
		</ul>
	</div>
</div>

<?php endif; ?>

<!-- part of the sidebar.php code removed for brevity. --> 

<div class="box">

	<div class="box_title">Search</div>

	<div class="box_content">
		<?php @include(TEMPLATEPATH . '/searchform.php'); ?>
	</div>

</div>
<?php endif; ?>
</div>
</div>

Notes on Example(1):

Notice How I placed CODE-4 immediately before the start of the dynamic sidebar widgets.

The Emplode theme sidebar´s CSS classes and HTML tags are being used to style and structure the Most Viewed Posts list.

CODE-4 is added to the sidebar.php file located in the theme folder.

Real Example(2) | Where to Add CODE-4 | Diary Theme

This is where I added CODE-4 for the “Diary Theme” of this Blog (in the sidebar.php file).

<aside id="sidebar">
	<!-- Begin Social Icons -->
	<section id="socialIcons">
	
    <!-- part of the sidebar.php code removed for brevity. --> 
    
	<?php if(get_option('diary_contact_page')):?>
	<a href="<?php echo get_page_link(get_option('diary_contact_page')); ?>" id="butContact">Contact</a>
	<?php endif;?>
    <!-- part of the sidebar.php code removed for brevity. --> 
	</section>
   <!-- part of the sidebar.php code removed for brevity. --> 
    
    <!-- MOST VIEWED POSTS code by BOUTROS ABICHEDID. Placed above the start of the Widgets-->
    <div class="sideBox">
    <h3>Most Viewed Posts</h3>
    <ul>
    <?php
    query_posts('meta_key=post_views_count&orderby=meta_value_num&posts_per_page=5');
    //If there are posts. checks to see if the current query has any results to loop over. 
    if (have_posts()) :
        //loop through the posts and list each until done. 
        while (have_posts()) : 
            //Iterate the post index in The Loop. 
            the_post(); 
            ?>
            <li><a href="<?php the_permalink() ?>" title="Permanent Link to: <?php the_title_attribute(); ?>"><?php the_title(); ?></a> <?php echo '(' . get_PostViews(get_the_ID()) .')'; ?></li>      
    <?php
        endwhile; 
    endif;
    //Destroy the previous query. This is a MUST.
    wp_reset_query();
    ?> 
    </ul>
    </div><!-- END OF MOST VIEWED POSTS. -->
    
	<?php // Widgetized sidebar 
        if ( ! dynamic_sidebar( 'sidebar' ) ) :?>
        <div class="sideBox">
            <h2>WIDGETS NEEDED!</h2>
            <p>Go ahead and add some widgets here! Admin > Appearance > Widgets</p>
        </div>
        <?php endif; ?>
</aside>

Notes On Example(2):

Notice How I placed CODE-4 immediately before the start of the sidebar widgets.

The Diary theme sidebar´s CSS classes and HTML tags are being used to style and structure the Most Viewed Posts list.

CODE-4 is added to the sidebar.php file located in the theme directory.

Styling Most Viewed Posts (CODE-4) | style.css

To style CODE-4 with CSS: Use the same styling as your sidebar´s Widgets (or your sidebar only in case your theme does not support widgets). You don´t have to do anything extra here unless you want to. Style it with what´s available for your theme. Same applies to the HTML tags, use the same layout available for your sidebar.

For instance if you are using Google Chrome browser use the “Inspect element” feature to know which CSS classes you need to use or you could inspect the source code. For Mozilla Firefox browser, you could either check the source code or install the Firebug Add-on. Also be aware that HTML tags for CODE-4 can also be changed or removed depending on your theme.

Disadvantage of the Code (CODE-4)

As I mentioned, CODE-4 is dependent on my previous tutorial´s Post View Counter codes which does not work with a caching plugin. Therefore, CODE-4 will not work with a caching plugin either. For instance, if you have W3 Total Cache or Quick Cache installed, the Post View Counter will not update and thus the Most Viewed Posts list can´t be accurately generated.

With all that said, if your WordPress Website is lightweight and your images are compressed and optimized for the Web, then by disabling the caching plugin, you might not notice a significant increase in page load time. You could also flush the buffer as I discussed in Tip8 in a past tutorial (as well you could implement other significant tips): 14 Tips for Maximum WordPress Performance & Speed.

For this blog, I am not using any caching plugin since I have multiple WordPress themes for my visitors to choose from.

To Recap! In case You are Confused

To display the Most Popular Posts Based on Views, first you need to add to your theme (CODE-1 and CODE-2) from my previous tutorial and then add CODE-4 of this tutorial.

How This Code Could be Improved

The code in this tutorial could be made as a customizable widget, so that non-technical users can easily integrate it into their blog from the WordPress dashboard (Appearance > Widgets panel). In this case you can place the Most Viewed Posts list anywhere you like on the sidebar. Widgets require no code expertise. They can be added, removed, and rearranged from the WordPress dashboard.

Your Turn to Talk

You now have the choice to Display the most Popular Posts (Based on Views) in your WordPress blog and without a plugin. This will hopefully entice your visitors to read more of your posts, thus reducing your blog´s bounce rate by viewing other pages and keeping your visitors longer on your Blog.

How easy did you find this tutorial to implement? Do you have something to add or anything else to say? If so, please share your opinion in the Comment section. Your opinion matters, unless it is a Spam.

Reference

If you found this post useful, please consider: linking back to it, subscribing by email to future posts, or subscribing to the RSS feed to have new articles delivered to your feed reader, or feel free to donate. Thanks!

About the Author |
Boutros is a professional Drupal & WordPress developer, Web developer, Web designer, Software Engineer and Blogger. He strives for pixel perfect design, clean robust code, and user-friendly interface. If you have a project in mind and like his work, feel free to contact him. Connect with Boutros on Twitter, and LinkedIn.
Visit Boutros AbiChedid Website.

56 Responses to “How To Display Most Viewed Posts in WordPress Without a Plugin”

  1. Abdul Ghani says:

    Hi Boutros,

    thanks for the tips.

    I’m wondering : I have a blog that lists links to external articles. The links are actually wordpress posts, but each post permalink is a link to external websites.

    Since your code above is based on views, would it be applicable to display popular “posts” in my setup ?

    Thanks

  2. Tomas says:

    Boutros, thank you very much for your clear instructions.
    Me too, like to avoid plugins so this is fantastic info

  3. Joe Porter says:

    Hello! thanks for the post about this… i have implemented it and it works just great! however one problem

    How can i view the most viewed posts today from ALL posts (not just the ones published today)?

    thanks for your help

  4. Tayssir says:

    hello plz how can i display
    Most Viewed post by CURRENT Category ?

    • Hi Tayssir,
      I am not sure what you mean exactly by current category.
      To display the Most Viewed Posts For a Specific Category, see item1 of the blockquote above (above CODE-4 References section)(if you don´t see the horizontal bar, and to scroll within the code, you can also click on the code window and use your keyboard´s arrow keys.)
      If you mean displaying the most viewed posts based on the currently user selected category where the category keeps changing depending on the selection of the user, then you need to set a variable for the current category ID (let say $cat_id is the variable). Then you replace the category ID constant by the $cat_id variable). For instance the number 76 from the code above (Item1 in the blockquote above CODE-4 References section) for the category ID will be replaced by the $cat_id variable.
      Thanks for your feedback.

      • Tayssir says:

        Thank you, yes i mean the category that user is browsing ,
        i change it to

            query_posts('meta_key=post_views_count&orderby=meta_value_num&posts_per_page=5&cat=$cat_id');

        and the result is Most viewed post in all category.
        Thanks for ur time

  5. DG says:

    OMG, my previous comment is quite screwed (if you’are moderating, I hope you can delete it), I’m so sorry LOL… Here I try to explain clearly:

    Which code should I use if I want to add PostView on template tag AND PostViews on the sidebar BUT NOT in Admin Area.

    I think I can understand if you just simply explain with CODE-1, CODE-2, CODE-3 or CODE-4.

    Thanks in advance and keep good works! :D

    • Hi DG,

      If you want to show Most Viewed Posts, but you don´t want to show the Post Views Column in your admin area (dashboard), then you can remove CODE-3 with the exception of get_PostViews() function, (line 12 to 19 of CODE-3), in addition of CODE-1 AND CODE-2, of the PREVIOUS tutorial.
      Then you need to add CODE-4 OF THIS tutorial.
      In this case
      CODE-3 modified becomes:

      Note: To scroll within the code: You can also click on the code window and use your keyboard´s arrow keys.

      <?php
      /**************CODE-3-MODIFIED***********
      @Author: Boutros AbiChedid
      *****************************************/
       
      //Gets the  number of Post Views to be used later.
      function get_PostViews($post_ID){
          $count_key = 'post_views_count';
          //Returns values of the custom field with the specified key from the specified post.
          $count = get_post_meta($post_ID, $count_key, true);
       
          return $count;
      }
      ?>
      

      Let me know, if you have any problems.

      Thanks.

  6. Alan says:

    Hi Boutros,

    Thanks a lot for this most useful tip!

    re: Juri says: February 14, 2012 at 11:24 AM

    Something I’m scratching my head about though…

    I can only get it to display most viewed posts with

    $current_month = date( 'M' ); // Jan-Dec
    $current_day = date('D'); // Mon-Sun

    which is kind of strange

    With m ( 01-12) or n (1-12), d (01-31) or j (1-31)
    no most viewed posts are displayed

    Also,
    $current-week = date('W');
    and
    query_posts("meta_key=viewscount&orderby=meta_value_num&year=$current_year&w=$current_week&posts_per_page=5");
    doesn’t display most viewed posts

    The wp_postmeta table contains postcount entries though, and
    echo date("D/M/Y");
    echo date("d/m/Y");
    echo date("j/n/Y");

    display correctly

    At first I though it could have something to do with the WP Settings > General Settings > Date Format so tried them out, no difference though

    Any clue?
    Best regards,
    Alan
    - WP 3.3.1
    - XAMPP 1.7.1

  7. Ichink says:

    Thank you for this information, I used it for my blog.
    But I remove it because error in my blog.
    Sorry, my english is very bad :(

  8. Ok thanks Boutros for your attention and explanation.

    Best regards.

  9. Hi Boutros.
    Thank you very much. I use the code for the footer widget on my blog and it works perfectly.
    I also use your Most Commented Widget code, and it works perfectly too. Now in my blog, I don’t need plugin again to make most commented widget.

    Thank you very much!

    By the way, can I republish this article in my blog without changing your copyright and keep the link back to you? Thank you.

    Oya, I’m sorry for my bad english. I hope you can understand what I mean.

    • Thanks Faisal. Your comment is much appreciated. I am glad you found my tutorials helpful to you.

      By the way, can I republish this article in my blog without changing your copyright and keep the link back to you? Thank you.

      Thank you Faisal for asking, as I’m sure that many people don’t.
      NO you can’t publish the tutorial in full (even if you put a link back to the original source). I don’t want any duplication of content.

      But what you can do, is publish the first 2-3 paragraphs of the post and at the end YOU CAN say: CONTINUE READING FROM SOURCE (put a link to my tutorial)

      See an example from my tumblr account (http://boutrosabichedid.tumblr.com/post/16667057498/display-most-viewed-posts-in-wordpress-without-a-plugin)

      Hope this helps.
      Boutros.

      • Ow lucky I have not republish this article on my blog. Thanks for the explanation.

        If I want to make an article about this on my blog with the words of my own without publishing a full copy of this article, is it still possible? I just want more people who know a good article like this and get the benefits I get. Thank you.

        • Hi Faisal,

          You can republish part of the article with a link back to the original source.
          As for the second part, you can with a link back to the original source. I am not sure how you can modify the code (you still have to link back to the original code).
          I don’t see why don’t you take the first 2-3 paragraphs of my post (add some more contents to it if you like) and continue the post with a link to the original source. That’s what most people do.
          See An example: http://seopep.blogspot.com/2011/10/how-to-turn-your-wordpress-blog-from.html
          Thanks.
          Boutros.

  10. Juri says:

    Hi,
    is there any way to display only the most viewed posts of the day? And I guess keeping as default the most viewed at all in case there are not visits to any posts during a day.

    • Sure you can.

      replace Line 14 of CODE-4 with the following:

      //Display Most Viewed (Published) Posts for the Current day
      $current_year = date('Y');
      $current_month = date('m');
      $current_day = date('d');
      $post_num=7; //number of posts to display
      
      query_posts("meta_key=post_views_count&orderby=meta_value_num&year=$current_year&monthnum=$current_month&day=$current_day&posts_per_page=$post_num");
      

      The double quotes tell PHP to treat the enclosed as an expression. I am getting the current year/month/day, and telling query_posts() to output the posts for the current month/year/day.
      See reference:
      http://codex.wordpress.org/Function_Reference/query_posts

      If there are No posts for that day you can default back to the main code. You need to use an if .. else statement. I’ll let you figure that one out.

      Note: To scroll within the code: You can also click on the code window and use your keyboard´s arrow keys.

      Boutros.

      • PersonPerson says:

        In order to change it for the most viewed per month.. I changed it to this code. Is this the correct solution?

        //Display Most Viewed (Published) Posts for the Current month?
        $current_year = date(‘Y’);
        $current_month = date(‘m’);
        $current_day = date(‘d’);
        $post_num=7; //number of posts to display

        query_posts("meta_key=post_views_count&orderby=meta_value_num&year=$current_year&monthnum=$current_month&posts_per_page=$post_num");
        //rest of code here
        
        • Hi Brian,
          Thanks for your comment.
          Your query looks correct. Try it out. Also you don’t need the ‘$current_day’ variable, there is no need to declare it, if your aren’t going to use it
          Boutros.

  11. Juri says:

    Thanks Boutros!
    I’m trying to manage to get the code working for custom post type but still nothing, maybe beyond my skills

    I hope you can fix it, it will be very useful for everybody and will complete your CODE so that it will be really awesome!

    Looking forward for your update

    • Hi Juri,

      I tried very hard for the past couple of days to modify the code for custom post type and It did not work.
      The weird thing is that I can create Custom Post types in the admin, but their URL takes me to a 404 page, and when I reset the permalinks (Settings -> Permalinks), I get this weird error “Catchable fatal error: Object of class WP_Error could not be converted to string in…”
      I looked in probably 100 different places for a solution and nothing worked.

      I managed to get the ‘Views’ Column for custom post types but I wasn’t able to populate the count.
      To get the ‘Views’ column to show for Custom Post Types make sure to add the “supports” (especially for title, editor, and custom-fields elements) array to the ‘register_post_type()’ function like so:

      <?php
      //Put this in functions.php file
      add_action( 'init', 'create_new_post_type' );
      function create_new_post_type() {
          register_post_type( 'multiple_products',
              array(
                  'labels' => array(
                  'name' => __( 'Products' ),
                  'singular_name' => __( 'Product' )
                  ),
              'public' => true,
              'has_archive' => true,
      	    'supports' => array('title','editor','excerpt','thumbnail','custom-fields'),
              )
          );
      }
      ?>
      

      I believe that CODE-1, CODE-3 (from the previous tutorial) AND CODE-4 (from this tutorial) all have to be modified to count for custom post types.

      If you find a solution, please let me know and I’ll update the code with proper credit to you.
      Sorry!
      Boutros.

      • PersonPerson says:

        Hi Boutros… THis is a great post.. I’ve implemented the code and it works great, but I’d like to change the code above to be for most viewed per month.. How would that work?

  12. Juri says:

    Hi,
    first of all Thanks a lot this is a simple way to avoid plugins, I have two questions:

    1)it doesn’t get more than one post. I set up the CODE 1 and the CODE 2 in single.php, than I put the CODE 4 in a php widget.
    Looks like everything is ok but it displays only one post.

    Also I tried to remove the POST PER PAGE, in my settings–>general there is 10 posts….

    I used the post per page in other query in the site and it always worked

    Do you know why?

    2) Can I use it for custom post, do I need to put in the query post_type and category?

    • Hi Juri,
      CODE-1 should be in ‘functions.php’ file
      CODE-2 should be in ‘single.php’ file
      CODE-4 could be in a widget (I am planning to do that in another tutorial, widgetizing the code). It is now in the ‘sidebar.php’. I haven’t tested it in a widget format to see how/if it works.

      The code does not work if you have a caching plugin in your theme.

      You set the ‘posts_per_page’ parameter of the query_posts() function on line 14 of the code to whatever number you want to display on your Blog. if you totally remove ‘posts_per_page’ parameter (if you removed &posts_per_page=5), then the displayed posts will default to whatever number you set it in your dashboard (Administration > Settings > Reading).
      I am not sure what’s your question there.

      The code now does not track Custom_Post_Types. The ‘post_views_count’ custom field name is not created for post-types. CODE-1 only track posts and not post_types, therefore CODE-1 need to be modified also.
      Since I don’t use custom post types on this blog, I can’t tell what need to be changed without testing. That’s something will be on the ‘to do’ list for me, Modifying the code for custom post types.
      Stay Tuned.
      Boutros.

      • Juri says:

        CODE 1 is in functions.php
        CODE 2 is in single.php
        CODE 4 is in a widget

        The problem is that is showing only one post whatever settings or post_per_page are.

        Also I tried to put CODE 4 in sidebar, before the dynamic widget area and it doesn’t show up at all.
        So I put the CODE 4 back in the widget and it shows only 1 POST.

        What’s wrong?

        Thanks

        • Hi Juri,
          If you are using a free WordPress theme that I can have access to (link?). I will take a look and see what’s the problem.
          And What version of WordPress you have? Also let me know what plugins you are using on your theme (names/links), as plugins can interfere with my code.
          Thanks.

        • Juri says:

          Hi Boutros,
          I’m using WP 3.3.1 and I tried to disable all plugins except 2 plugins that make my site works, but it still displays only one post.
          Plugins are:
          http://wordpress.org/extend/plugins/custom-content-type-manager/
          http://wordpress.org/extend/plugins/php-code-widget/

          Here it’s the theme: http://uploading.com/files/cbca78fe/pim-newspaper-magazine-and-blog-template.zip/

          Also I noticed that is getting the most viewed post only among 2 posts that belongs to the same category, other posts have more views but don’t show up. There should be some conflict.

          Hope you can help me

          Thanks

        • Hi Jury,

          I tried your Pim Theme on my Blog. I put:
          CODE-1 (AND CODE-3) in functions.php
          CODE-2 in single.php
          CODE-4 in sidebar.php (you are right CODE-4 should be widgetized) since your sidebar.php file only allows for Widgets.
          So placing CODE-4 in ‘sidebar.php’does not display anything since this is the way your Pim theme is coded to allow widgets.

          I placed CODE-4 separately in the ‘header.php’ file and then in the ‘footer.php’ file and then in the ‘index.php’ file to see if the MOST VIEWED POSTS list is correct, and it is as you see in the images below. My code works fine for regular posts. Even the Posts count in the Admin panel are displaying an accurate count for post Views.
          Remember, that my blog does not have any “custom-post-types” and, If CODE-4 is not working properly in your case, I suspect because of the custom post types. I know that my code right now does not take into accountcustom-post-types.

          Pim theme as it appears for my Blog In Header:
          Pim theme in header.

          Pim theme as it appears for my Blog In Footer:
          Pim theme in footer.

          Pim theme as it appears for a single post:
          Pim theme in Single post.

          Post View count in the dashboard When Pim theme in activated:
          Pim theme in dashboard.

          FOR TESTING PURPOSES: place CODE-4 IN ‘header.php’ or ‘index.php’ and see if you are getting an accurate posts views count. If you are not, then the problem is the ‘custom content types’.
          Let me know how it goes.
          Boutros.

        • Juri says:

          Great Boutros!
          I think I had only to add the CODE-3 to make it work.
          It works in widget and file templates as well like a charm!

          I was trying to make it works for custom post as well:

          I added the CODE-2 in single-(post_type).php
          The “Views” column in the post type admin appears and displays the right views number
          I tried to edit the CODE-4 and I used a different query:

          <?php global $wp_query;
          $args = array(
                  'post_type' => 'videopagine',
                  'meta_key' => 'post_views_count',
                  'orderby' => 'meta_value_num',
           );
          $query = new WP_Query( $args );
          ?>
          

          I think it’s almost done, it displays 3 custom posts type, great!
          But doesn’t get the the most viewed post.

          What does it need to do last?

          Thanks

        • Hi Jury,

          Great I am glad you get it working so far.
          As for custom post types (I don’t use any on my blog). Therefore, I have to create a new testing environment which will take me some time to do (along with all my regular work that I have to do)
          I’ll keep that in mind, hopefully in the next few days I have an update for the code to incorporate custom-post-types.
          In the meantime, If you manage to get the code working for custom post types. Please add it here, for everybody else to learn.
          Boutros.

        • Juri says:

          Sorry the php in the previous post is missing something, here it’s a pastebin http://pastebin.com/wG24dAEN

        • That’s OK Jury. I fixed it for you.
          For next time if you want to add a snippet of PHP code:

          use*:
          {php}
          Some code here….
          {/php}

          * Replace { with [ and replace } with ]
          Boutros.

      • Juri says:

        Still can’t find a way to make it works with custom post, nobody found a solution?
        It’s gonna be huge if we do it!!!