Title: get_posts with if statements
Last modified: August 19, 2016

---

# get_posts with if statements

 *  Resolved [peters2007](https://wordpress.org/support/users/peters2007/)
 * (@peters2007)
 * [15 years, 9 months ago](https://wordpress.org/support/topic/get_posts-with-if-statements/)
 * I’m going to look like a real dunce here, because I’m really not au fait with
   PHP – I’m learning it by osmosis as I go along! – but I’m wondering if someone
   could help me to achieve what I’m trying to do.
 * At the top of the content area on my index page, I am using the Loop to display
   a _maximum_ of two posts from a “top stories” category, Category 17 – note that
   this category does not always contain the full two posts. I am then using another
   loop further down the page to display posts _not_ from Category 17.
 * However, I want to ensure that there are always _four_ posts displayed on my 
   home page at any one time. If there is one post in Category 17, I would like 
   the second loop to display three posts. If there are two or more posts in Category
   17 (i.e. two are displayed on the front page), I would like the second loop to
   display only two posts. If any other condition holds (i.e. if there are no posts
   in Category 17), I would like the second loop to display four posts.
 * Here is what I have for the second loop:
 *     ```
       <?php
       if (get_category('17')->category_count == 1) {
       	$nontop = "'numberposts=3&cat=-17'";
       }
       elseif (get_category('17')->category_count > 1) {
       	$nontop = "'numberposts=2&cat=-17'";
       }
       else {
       	$nontop = "'numberposts=4&cat=-17'";
       }
       	global $post;
       	$myposts = get_posts($nontop);
       	foreach($myposts as $post) :
       	setup_postdata($post);
       ?>
   
       ----------stuff to display each post----------
   
       <?php endforeach; ?>
       ```
   
 * Instead of outputting 3, 2 or 4 posts, this currently leads to 5 posts being 
   displayed. I’m clearly making an elementary error of some sort, but I don’t know
   what! Alternatively, if there’s a more common-sense way to approach this, I’d
   gladly accept advice.

The topic ‘get_posts with if statements’ is closed to new replies.

## Tags

 * [categories](https://wordpress.org/support/topic-tag/categories/)
 * [category](https://wordpress.org/support/topic-tag/category/)
 * [loop](https://wordpress.org/support/topic-tag/loop/)
 * [php](https://wordpress.org/support/topic-tag/php/)

 * In: [Fixing WordPress](https://wordpress.org/support/forum/how-to-and-troubleshooting/)
 * 0 replies
 * 1 participant
 * Last reply from: [peters2007](https://wordpress.org/support/users/peters2007/)
 * Last activity: [15 years, 9 months ago](https://wordpress.org/support/topic/get_posts-with-if-statements/)
 * Status: resolved

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
