0

I have this code to show recent posts from one category. I need to show only the posts which have comments. How can i do that via shortcode?

/* Shortcode to output recent posts from one category */

function display_cat_recent_posts() {
$args = array(
'post_type' => 'post',
'posts_per_page'=> 5,
'cat'=> 10,
);
$cat_recent_posts = new WP_Query( $args );
if( $cat_recent_posts->have_posts() ):
$output = '<ul>';
while ( $cat_recent_posts->have_posts() ) : $cat_recent_posts->the_post();
$output .= '<li><a href="' . get_permalink() . '" title="' . get_the_title() . '">' . get_the_title() . '</a></li>';
endwhile;
$output .= '</ul>';
endif;
return $output;
wp_reset_postdata();
}
add_shortcode( 'recent-posts', 'display_cat_recent_posts' );

Thank you...

0

Since you are in a loop you can use the function get_comments_number().

Retrieves the value of the total number of comments, Trackbacks, and Pingbacks for a post. This tag must be within The Loop. Unlike comments_number() this function will return the value as a numeric value.

Use it for example as follows:

$num_comments = get_comments_number();

if ( $num_comments > 0 )
    $output .= "...";

So your code could look like this:

/* Shortcode to output recent posts from one category */
function display_cat_recent_posts() {
  $args = array(
    'post_type' => 'post',
    'posts_per_page'=> 5,
    'cat'=> 10,
  );

  $cat_recent_posts = new WP_Query( $args );

  if ( $cat_recent_posts->have_posts() ):
    $output = '<ul>';
    while ( $cat_recent_posts->have_posts() ) : $cat_recent_posts->the_post();
      if ( get_comments_number( ) > 0 ):
        $output .= '<li><a href="' . get_permalink() . '" title="' . get_the_title() . '">' . get_the_title() . '</a></li>';
      endif;
    endwhile;

    $output .= '</ul>';
  endif;

  return $output;

  wp_reset_postdata();
}

add_shortcode( 'recent-posts', 'display_cat_recent_posts' );
|improve this answer|||||
  • how can i use this with the function (shortcode) above? – Christopher Jun 6 '13 at 9:38
  • I improved my answer for you – Mike Madern Jun 6 '13 at 9:42
  • I put this code in function.php but didn't work... – Christopher Jun 6 '13 at 10:23
  • Thats useful information. What didn't work? Did you get a kind of error (if so, what did the error show), what have you tried to make it work? "didn't work" isn't enough to work with. – Mike Madern Jun 6 '13 at 10:49
  • When i use it without if ( get_comments_number( ) > 0 ): i get 5 post from the category. When i use it with if ( get_comments_number( ) > 0 ): i get nothing for output... – Christopher Jun 6 '13 at 11:24

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.