WordPress.org

Ready to get started?Download WordPress

Forums

Problem limiting link list to one category (2 posts)

  1. Gregg Banse
    Member
    Posted 7 years ago #

    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;
    
  2. Gregg Banse
    Member
    Posted 7 years ago #

    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; ?>

Topic Closed

This topic has been closed to new replies.

About this Topic