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!

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 PHP for WordPress PHP Basics for WordPress The Loop

I don't understand the colon inside the loop

I don't understand how the sections connect to each other. Like "while ( have_posts() ) : the_post();" I don't see where it finds the connecting colon further down in the code.

2 Answers

Genevieve Herres
Genevieve Herres
Courses Plus Student 3,457 Points

This is actually a PHP structure. In PHP you can have your while loop enclosed with curly braces or using colon and endwhile. Both are completely legal.

Example with curly braces: while ( have_posts) { the_post(); //more code }

Example with colon and endwhile: while ( have_posts) : the_post(); // more code endwhile;

The fact that while ( have_posts) : the_post(); is all on the same line is just shorting of the code. PHP isn't very picky about whitespace.

For more information, see the PHP manual: http://php.net/manual/en/control-structures.while.php

Liam Maclachlan
Liam Maclachlan
22,805 Points

To add to this (and slightly off topic), you can also omit the colon or curly braces completely if you are own running a single line of code, or another conditional, in the conditional. Some examples:


// simple single line example 
if ( true )
    return true;

// also works without the dropped line
if ( true ) return true;

// simple single line conditionals example with else
if ( true )
    echo 'got it';
    echo 'not got it';

// single line foreach with multiline if statement
foreach ( $items as $array )
    if ( in_array( 'needle', $array ) ) :
        // do lots of stuff here
        $var = 'string';
        $var .= ' with more attached';
        echo $var;

Ohhhh, I see! It's in place of the curly braces. Thanks!