The Loop consists of PHP and HTML code that gets and displays posts for a page. The Loop is a key component of a WordPress theme. Code 2. The Loop's Basic Code
Loop basicsWhen broken down to its simplest form (Code 2), The Loop is actually quite simple: <?php if (have_posts()) : ?> This starts by querying the database to determine whether there are posts to display. If there are, the next commands are executed; if not, WordPress skips ahead to the end of The Loop. <?php while (have_posts()) : the_post(); ?> This line of code tells WordPress to get post information. It starts The Loop's actual loopa collection of code that is repeated for each item. In this case, the code inside the loop is repeated for each post. The actual number of posts it is repeated for is determined by WordPress settings, as discussed in Chapter 2. <?php the_content(); ?> This line tells WordPress to display the contents of the post. <?php endwhile; ?> This closes the loop when the specified number of posts have been retrieved and displayed. <?php endif; ?> This is the end of The Loop. Beyond the BasicsOf course, Code 2 is an extremely basic example. Although it will work in an index.php file as istry it and see for yourself!it omits much of the information readers expect to see, such as the post title, the post author, the post date, and so on. To add this information, insert the appropriate tags between the second and fourth line of this example. Tips
The Loop in the Default themeIn the Default theme, The Loop is much more complex. Code 3 on the next page shows the code required by The Loop in black and additional content and formatting code in gray. As you can see, this version of The Loop includes far more template tags. It also calls on other worker files, with their own template tags, that are part of the theme. All these tags send requests to the database and display the results that include the post title, the author name, the post date, and comment links (Figure 1). If there is nothing to display, WordPress tells you and displays a Search form (Figure 8). Figure 8. The Default theme displays a Search form if there are no posts to display.The post in The LoopThe contents of the blog post itself is represented by one single line of code within The Loop. In Code 2, it's <?php the_content(); ?>, which simply displays the post content. In Code 3, from the Default theme, it's <?php the_content('Read the rest of this entry »'); ?>. This includes instructions to create a link to any part of the post that follows a special <!--more--> tag inserted by the post author within the post. The wording of the link is: Read the rest of this entry ». Code 3. The Loop in the Default theme's index.php file
|