Question

I hope somebody would be kind enough to help. I currently have a page that orders all of the posts by comment count, but I want to change the loop to order the posts by view count. I have installed the 'wp-postviews.1.50' plugin and have got it to display the number of views on each post, so I know that side of it is working, now I just need the loop code changed to order by most views, is this possible?

This is the how the number of views is called out:

<?php $views = get_post_meta($post->ID, 'views', true); ?><?php echo $views; ?>

And here is the loop I need changed:

<?php $posts_per_page = get_query_var('posts_per_page'); ?>
<?php $paged = intval(get_query_var('paged')); ?>
<?php $paged = ($paged) ? $paged : 1; ?>
<?php $args = array(
'posts_per_page' => $posts_per_page,
'paged' => $paged,
'more' => $more = 0,
'orderby' => 'comment_count',
'order' => 'DESC',
); ?>
<?php query_posts($args); ?>
<?php if (have_posts()) : while (have_posts()) : the_post() ;?>
<div <?php post_class() ?> id="post-<?php the_ID(); ?>">

Thanks in advance for any help with this.

I'm using WordPress 3.0.4.

Was it helpful?

Solution

Just wanted to give an update. Someone was kind enough to show me how to update the code I posted above. It turned out to be quite simple (if you know what you're doing!). So I have posted it below for anyone that wants to do something similar.

<?php $posts_per_page = get_query_var('posts_per_page'); ?>
<?php $paged = intval(get_query_var('paged')); ?>
<?php $paged = ($paged) ? $paged : 1; ?>
<?php $args = array(
'posts_per_page' => $posts_per_page,
'paged' => $paged,
'more' => $more = 0,
'meta_key' => 'views',
'orderby' => 'meta_value_num',
'order' => 'DESC',
); ?>
<?php query_posts($args); ?>
<?php if (have_posts()) : while (have_posts()) : the_post() ;?>
<div <?php post_class() ?> id="post-<?php the_ID(); ?>">

OTHER TIPS

From the plugin documentation

To Display Most Viewed Posts Use:

<?php if
(function_exists('get_most_viewed')):
?>
<ul>
      <?php get_most_viewed(); ?>    
</ul> <?php endif; ?> 

The first value you pass in is what you want to get, 'post', 'page' or 'both'. The second value you pass in is the maximum number of post you want to get.

Default: get_most_viewed('both', 10);

Try with this:

$args=array(
 'posts_per_page'      => 15, 
 'post_type'     => 'post', 
 'key' => 'views',
 'orderby' => 'meta_value_num', 
 'order'    => 'ASC',
 'post_status' => 'publish'
);

query_posts($args); ?>
 <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

I've made it this way pretty nicely :)

<?php $args = array(
  'posts_per_page' => 4,
  'category_name' => 'xyz',
  'meta_key' => 'views',
  'orderby' => 'meta_value_num',
  'order' => 'DESC',
  'post_status' => 'publish'
); ?>
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top