The Famous ‘Loop’ in WordPress
The ‘Loop’ in WordPress
When working with real WordPress content, the ‘Loop’ is one of the most essential parts of WordPress coding paradigm. It helps us loop over content in WordPress like posts, pages and any other custom post types.
What constitutes a Loop in WordPress?
The ‘Loop’ in WordPress consists of a While(){ }
loop inside of which we use some special predefined WordPress functions like have_posts()
, the_post()
, the_title()
& the_content()
to pull the content from the WordPress database onto the front end of the site.
The code syntax is as below:
<?php
while(have_posts()){ //keep looking as long as we still have posts to loop through.
the_post(); //gets all post information ready for use.
?> //drop out of php to enter HTML mode.
<h2><?php the_title(); ?></h2> //outputs the post title.
<p><?php the_content(); ?></p> //outputs the content of the post.
<?php //drop back in php mode.
}
?>
Depending on the URL you visit on a WordPress site, WordPress is going to use different template files in your theme folder to control what you see on the screen. Even though we have different files like page.php, index.php & single.php etc, they all have one very important thing in common and that is that they all use the famous ‘Loop’ in WordPress.
It is a general pattern of doing something once for each item in a collection even if that collection has only one item in it.
In a WordPress universe, the loop is a famous term. Any WordPress developer will know what you are talking about if you mention the ‘Loop’.
The ‘Loop’ is at the heart and soul of WordPress and something that you will use again and again during WordPress website development.
No Comments