1

How do I show popular post by category code

I have add code

<?php 
$popularpost  = new WP_Query( array( 
    'cat'=> 2, 
    'posts_per_page' => 1, 
    'meta_key' => 'post_views_count', 
    'orderby' => 'meta_value_num', 
    'order' => 'DESC'  
) ); 
query_posts($popularpost); 
if (have_posts()) : 
    while (have_posts()) : 
        the_post(); ?>
        <li><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
        <?php 
    endwhile; 
endif; 
wp_reset_query(); 
?>

but my code is not correct.

Any ideas?

0

You are running two queries in one. You should only run one, and definitely not with query_posts. You should never ever use query_posts

Note: This function isn't meant to be used by plugins or themes. As explained later, there are better, more performant options to alter the main query. query_posts() is overly simplistic and problematic way to modify main query of a page by replacing it with new instance of the query. It is inefficient (re-runs SQL queries) and will outright fail in some circumstances (especially often when dealing with posts pagination).

You should only use WP_Query or get_posts for custom queries. Your query should have the following format

<?php 
$popularpost  = new WP_Query( array( 
    'cat'=> 2, 
    'posts_per_page' => 1, 
    'meta_key' => 'post_views_count', 
    'orderby' => 'meta_value_num', 
    'order' => 'DESC'  
) );

if ($popularpost->have_posts()) {
    while ($popularpost->have_posts()) {
        $popularpost->the_post(); ?>
        <li><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
        <?php 
    } 
    wp_reset_postdata();
} 
?>
  • i'm add code to index.php but don't show any thing? how to cheking it's? – DinhTv Mar 19 '15 at 15:16
  • Sorry, had a slight problem there. Corrected my code – Pieter Goosen Mar 19 '15 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.