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.