0

I am new to creating a theme and wonder if anyone can help?

I am trying to display all the featured images from posts under a specific category (id=5) on my index page and it's not working using the following code:

<?php 
$myblogPosts = new WP_Query('cat=5'); // Cat 5 is the blog category.
if ($myblogPosts->have_posts()) :
while ($myblogPosts->have_posts()) : $myblogPosts->the_post();
?>
<div class="hero_img"><?php the_post_thumbnail(); ?></div> <!--Post image-->
<?php endwhile; 
else : ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

Can anyone see why it's not working? All I get is the "Sorry, no posts" displayed where the image should be.

BTW, I got the cat id from this URL (http://localhost:8888/wp-admin/edit-tags.php?action=edit&taxonomy=category&tag_ID=5&post_type=blog)

Thanks in advance!!

2
  • This may seem like a silly question, but do you actually have any post in category 5? for example if you change it to 'cat=1' which by default is the Undefined category do you get anything back?
    – Aron
    Jan 17, 2015 at 19:42
  • Hi Aron, hmm, this is strange. The post comes up when I change it to 'cat=1' but it is definitely under 'cat=5' too as selecting the count in the category takes me to the post that I wanted to display.
    – Nibbers
    Jan 17, 2015 at 22:48

1 Answer 1

0

From the url you supplied it looks like you are using a custom post type of blog. The most likely reasons you are not seeing the post you want to display is that by default WP_Query is only set to display posts - see WordPress Codex on WP_Query Post & Page Parameters for more info.

So for your WP_Query to return the post you are after you will need to replace line 2:

$myblogPosts = new WP_Query('cat=5'); // Cat 5 is the blog category.

With something more like this:

$args = array( 'post_type' => 'blog', 'cat'=> 5); // Cat 5 is the blog category.
$myblogPosts = new WP_Query($args);
2
  • That is absolutely brilliant! Thank you so much and sorry for my total noobness!
    – Nibbers
    Jan 18, 2015 at 0:25
  • ah you're welcome @Nibbers and don't worry I have been working with WP for ages now but still get caught out by things like this lol
    – Aron
    Jan 18, 2015 at 0:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.