WordPress.org

Support

Support » How-To and Troubleshooting » Problem limiting link list to one category

Problem limiting link list to one category

  • We have 2 categories set up. One is for posting (category ID=1) the other is for sidebar announcements (category ID=2, using the sidebar plugin).

    What I’m trying to do is to only show the titles of the main category posts in a Recent Posts listing. Without the in_category(‘1’) function all posts – including those from the sidebar display as they should (except that I don’t want the post from the sidebar category). When I add the in_category(‘1’) function, the list is limited to only 3 of the 5 posts that are currently in the main cat (ID=1). The other two links are shown on the next page as are their summaries. The sidebar categories are excluded as I expected.

    I’m missing something in how the code works but I can’t seem to find it.

    The following code is what I have in place.

                if ( $recentposts = $wpdb->get_results("SELECT ID, post_title FROM $wpdb->posts WHERE post_status = 'publish' AND post_date_gmt < '$today' ORDER BY post_date DESC LIMIT 10")):
                        foreach ($recentposts as $post) {
                                 if ( in_category('1') ):
                                      if ($post->post_title == '')
                                          $post->post_title = sprintf(__('Post #%s'), $post->ID);
                                      echo "<div id="lcoltxt"><a href='".get_permalink($post->ID)."'>";
                                      the_title();
                                      echo '</a></div>';
                                 endif;
                        }
    
                endif;
    
Viewing 1 replies (of 1 total)
  • Here’s the solution:

    $today = current_time('mysql', 1);
              if ( $recentposts = $wpdb->get_results("SELECT $wpdb->posts.ID, $wpdb->posts.post_title FROM $wpdb->posts LEFT JOIN $wpdb->post2cat ON $wpdb->posts.ID = $wpdb->post2cat.post_id WHERE $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_date_gmt < '$today' AND $wpdb->post2cat.category_id = 1 ORDER BY $wpdb->posts.post_date DESC LIMIT 10")):
            ?>
            <?php
    
            foreach ($recentposts as $post) {
                     if ($post->post_title == '')
                         $post->post_title = sprintf(__('Post #%s'), $post->ID);
                     echo "<div class=\"lcoltxt\"><a href='".get_permalink($post->ID)."'>";
                     the_title();
                     echo '</a></div>';
            }
    
            ?>
            <?php endif; ?>
Viewing 1 replies (of 1 total)
  • The topic ‘Problem limiting link list to one category’ is closed to new replies.
Skip to toolbar