query_posts() vs get_posts() multiple loops

I have a template which initially had one single loop and it was using query_posts, I added 2 more loops using the same method, However after reading allot about these it was concluded that I shall stop using it and everyone is against using it.

original query_posts loop (latest posts)

Read More
<?php if ( !is_front_page() && tfuse_options(PREFIX.'_pagination_portfolio') ){
    $cat = get_query_var( 'cat' );
    query_posts( array ( 'posts_per_page' => -1, 'cat'=>$cat ) );
}
while (have_posts()) : the_post(); ?>
    //blah posts here
<?php endwhile; ?>

2nd custom get_posts loop (random posts)

<?php if ( !is_front_page() ){
    //$cat = get_query_var( 'cat' );
    $args = array( 'numberposts' => 10, 'orderby' => 'rand' );
    $rand_posts = get_posts( $args );
}
foreach( $rand_posts as $post ) : ?>
    //blah posts here
<?php endforeach; ?>

3rd custom get_posts loop no working (most viewed posts)

if ( !is_front_page() ){
    $cat = get_query_var( 'cat' );
    $args = array( 'v_sortby' => 'views', 'v_orderby' => 'DESC', 'numberposts' => 10, 'cat'=> $cat);
    $most_viewed_posts = get_posts( $args );
}
foreach( $most_viewed_posts as $post ) : 
    //blahblah
<?php endforeach; ?>

The problem is that the third loop doesnt show the right posts, as if it doesnt recognize the post meta, however if i use query_posts then it works!

views v_sortby, v_orderby

Any help is appreciated, I am quite new to this.

Update
According to similar question asked on this site. below is another way of achieving it using query_posts with meta keys. I guess there is a better way of rewriting the code to use meta keys + wp_query or get_posts someone care to? I am very new to this, looks too chunky? :S

<?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(); ?>">

Related posts

Leave a Reply

1 comment

  1. Thanks to tips given by the commentators I was able to achieve this 🙂

        <?php 
    if ( is_front_age() ){
                        $most_viewed_posts = new WP_Query( array('v_sortby' => 'views', 'v_orderby' => 'DESC', 'showposts' => 10, 'cat'=> 3) );
                        }
                        while ( $most_viewed_posts->have_posts() ) : $most_viewed_posts->the_post(); ?>
    
    //post structure
    
     <?php wp_reset_postdata(); ?>