Hello, I need small help with php. This is my code which queries latest 5 post title from database. I would like to query commented and uncommented posts separately and wrote this code: <?php global $wpdb; $posts = $wpdb->get_results("SELECT * FROM wp_posts WHERE post_author = $id AND post_type = 'post' LIMIT 5 "); foreach ($posts as $post) { if ($post->comment_count >= 1) { echo '<li>' . $post->post_title . '</li>'; } else if ($post->comment_count < 1) { echo '<li>' . $post->post_title . '</li>'; } } ?> PHP: But there is one big problem. If the latest five posts are all uncommented when I view commented posts it doesn't display anything. I know that it happens because of comparing comments number to 1 and showing posts only after it, but I don't know any better ways. Can anyone please help?
Uh you're putting them both in the same <ul>.. I see no difference between your if and else, the code is exactly the same: <li>$post->post_title</li> .. So you need to do two separate queries: Add " AND comment_count = 0 " for uncommented posts, and " AND comment_count > 0 " to get the commented posts.
You don't need to put separate queries. You can do it in one query. SELECT * FROM wp_posts WHERE post_author = $id AND post_type = 'post' AND post_comment > 1 LIMIT 5 UNION SELECT * FROM wp_posts WHERE post_author = $id AND post_type = 'post' AND post_comment = 0 LIMIT 5 Code (markup): The reason why you don't want to split it into 2 queries is because it's more efficient to put it in one query (it's faster performance)
Yeah, I just suggested two queries because it's going to be easier for him to integrate that in two different <ul> - but yeah, yours is faster.