Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Wordpress Theme Functions & WP_Query

I've just watched the 'Displaying Custom Posts and Fields in a Template' video in the 'How to Build a WordPress Theme' course and have a question about the use of WP_Query.

The variable $the_query is set up as a new WP_Query with the appropriate arguments. Then the standard Loop is modified so that the while loop and the_post() function both use $the_query.

My question is why isn't the if statement modified to use $the_query as well? Wouldn't the if statement continue to use the default query instead of the custom query?

Thanks for your help!

1 Answer

Matt Campbell
Matt Campbell
9,767 Points

You don't actually need to use the if statement. All it does is just check to see if there are any posts at all, I suppose you could apply to query to it to echo out an error if there's no posts relating to your query.

Personally, I never use the if statement in my code. Just while and the_post.

Thanks Matthew, and if I understand it correctly, and I can see why it might be possible to leave it out.

However, my question is specifically about this:

if ( have_posts() ) :  while ( $the_query->have_posts()) : $the_query->the_post();

Why does the first have_posts() not need to have $the_query-> in front of it?

Matt Campbell
Matt Campbell
9,767 Points

Because it's just a general check to see if there are any posts at all in the database. I can't see why you couldn't apply the query to it, so that if there's no posts in this post_type then display this message, for example.

The query effects what WP looks for in the database, the query basically, as it's just a general check, there's no need to apply the query to it. If there's no posts, there's no posts. It's a very general thing and the only time it's ever really valid is when a theme is first installed although there's always the sample post so again, not really very useful. Suppose if someone were to delete all the posts it's better to have a message then blank space.

I understand what you are saying but surely in the case of a custom query the purpose of the if statement is to see if there are any results to the custom query, as opposed to any posts at all in the database?