WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Most Popular in one category (6 posts)

  1. mkjar
    Member
    Posted 3 years ago #

    Is there a way that I can get only the most popular posts in specified category? the code I am using currently in template is below:

    <h2>Most Popular</h2>
    <ul class="mostpop">
    <?php $result = $wpdb->get_results("SELECT comment_count,ID,post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , 10");
    foreach ($result as $post) {
    setup_postdata($post);
    $postid = $post->ID;
    $title = $post->post_title;
    $commentcount = $post->comment_count;
    if ($commentcount != 0) { ?>
    <li><a href="<?php echo get_permalink($postid); ?>" title="<?php echo $title ?>">
    <?php echo $title ?></a></li>
    <?php } } ?>
    </ul>

    thanks for your help!!

  2. MichaelH
    Member
    Posted 3 years ago #

    Assuming by popular you mean the post with the most comments then this should get the post with the highest comment count for a given category

    <?php
    $cat_id = get_cat_ID('your-category-here');
    $args=array(
      'cat' => $cat_id,
      'orderby' => 'comment_count',
      'order' => 'DESC',
      'post_type' => 'post',
      'post_status' => 'publish',
      'posts_per_page' => 1,
      'caller_get_posts'=> 1
    );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
        <?php
      endwhile;
    }
    wp_reset_query();  // Restore global post data stomped by the_post().
    ?>
  3. Mark / t31os
    Moderator
    Posted 3 years ago #

    The user was pulling 10 posts in the original query Michael..

    'posts_per_page' => 10,

    A pre-emptive response to "The query is only returning one post"... ;)

  4. mkjar
    Member
    Posted 3 years ago #

    thanks!

  5. MichaelH
    Member
    Posted 3 years ago #

    You are welcome. Marking this resolved.

  6. mkjar
    Member
    Posted 3 years ago #

    it worked like a charm! thanks so much!

Topic Closed

This topic has been closed to new replies.

About this Topic