WP: The Loop

Building on top of the previous post, let’s go ahead and add the famous “WordPress Loop” to the index.php of our theme. It’ll help to fetch and display blog posts on the site.

In the previous post, we had the following code in index.php

<?php
    bloginfo('name');
    bloginfo('description');
?>

Let’s change that to –

<h1> <?php bloginfo('name'); ?> </h1>
<p> <?php bloginfo('description'); ?> </p>
 
<?php

while (have_posts()) {

	//fetches post, keeps track of count
	the_post();
	?> 
 
	<h2> <?php the_title(); ?> </h2>
	<p> <?php the_content(); ?> </p>

	<?php
}
?>

The code above fetches blog name and wraps it in h1 header. It also fetches blog description and wraps it in p paragraph tag.

Next, it goes into the while “loop”.

The while loop there checks have_posts() function. If it returns true, it’ll continue to execute everything inside of it.

Inside the while loop, we have the_post() function which fetches the post data and keeps track of the count. This allows us to use functions like the_title() and the_content() to output the title and content of the blog post.

It continues to do so as long as there are posts. This means changing our new theme’s index.php file to the code above will output all the blog posts on the site.

Leave a comment