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

Liam Maclachlan
Liam Maclachlan
22,805 Points

Why does this loop need '$the_query->the_content();' so it doesn't break?

So, I'm using a custom post type. When I call the post type, I was having problems with getting the content to screen. That is no longer a problem but could you answer for me why

    $the_query->the_content();
    $the_query->the_post();

are needed in this loop, and why I simply can't just call the 'the_content()' function

            <?php 
                $args = array(
                        'post_type' => 'Information'
                    );

                // The Query
                $the_query = new WP_Query( $args );

                // The Loop
                if ( $the_query->have_posts() ) {
                    while ( $the_query->have_posts() ) {
                        $the_query->the_content();
                        $the_query->the_post();
                        the_content();

                    }
                } else {
                    echo 'An error has occured. Please contact the site administrator';
                }
                /* Restore original Post Data */
                wp_reset_postdata(); 
            ?>

any insight would be greatly appreciated. I don't fully understand why I need to call the content form the object before it will display (the page doens't load without those 2 lines)

1 Answer

$the_query->the_post(); Must come first, because this function sets up the post. So the_post() function retrieves the information about the post and after information is set, you can then begin to display the title, content, and other information.

More info here:

<?php
if ( have_posts() ) {
    while ( have_posts() ) {

        the_post(); ?>

        <h2><?php the_title(); ?></h2>

        <?php the_content(); ?>

    <?php }
}
?>
Liam Maclachlan
Liam Maclachlan
22,805 Points

That's what I thought but just wanted to clear it up. Thanks man :)

Liam Maclachlan
Liam Maclachlan
22,805 Points

Actually, one more thing to clear up. Why is it then that I can't simply call

$the_query->the_post;

the_content();

but have to instead call.

$the_query->the_post();
$the_query->the_content();
the_content();

Does $the_query->the_post not contain all the relevant object informaiton of the content and it's custom fields?