Part 4: How to Implement Post Loop in WordPress?

WordPress loop is actually a code, used to display the main content and excerpts of content on your WordPress blog. In simple, this WordPress loop is used to display posts. It is used in WordPress theme, to display the posts on your WordPress website. It displays all the information, that the WordPress has about the posts. You can insert the post loop code wherever you want, mostly it is been placed in the index.php file. Since the index page by default will be your blog homepage. 
The basic syntax for post loop is

<?php if(have_posts()) {
while(have_posts()) {
the_post(); // post content here
}
} endwhile;
endif;
?> 

Initially, the loop starts checking that, the current webpage should display multiple lists of posts or a single post. If the page has to be displayed with the list of posts, then it will list the title and excerpt for each post. Or if the page to be displayed with a single post, it will just display the content of the page. If a visitor access for the page that doesn’t exist or if no page is available, then the loop will give an error message stating that there is no page or post available. 

Example post loop in WordPress

<?php if(have_posts()) : while(have_posts()) : the_post(); ?>
<h2><?php the _title(); ?> </h2>
<?php the_post_thumbnail(); ?>
<?php the_excerpt(); ?>
<?php endwhile; else: ?>
<p> No posts available, Sorry!!!</p>
<?php endif; ?>

The lines of code <?php if(have_posts()) : while(have_posts()) : the_post(); ?>, <?php endwhile; else: ?>, <?php endif; ?> states that when there is blog post and when there is no blog post. 
The lines <h2><?php the _title(); ?> </h2>, <?php the_post_thumbnail(); ?>, <?php the_excerpt(); ?> will actually display the title, featured image, and excerpt of the post. 
while(have_posts()): the_post() → This part of code actually reads and the process of repeating as many times as there are posts. 
There are multiple things that loop can display such as
Next_post_link
Previous_post_link
The_author
The_category
The_content
the_ID
The-meta
The_shortlink
The_tags
The_title
The_time
You can even use conditional statements to display the different contents based on factors such as
Is_admin
Is_single
Is_page
Is_home
Is_tag
Is_category
Is_author
Is_404 and much more 
Note: You can use pagination to limit the number of posts that are looped through a page.

Conclusion

Both the post loops are important for displaying blog post.  It gives you a clear specification and makes your task easy. Hope you got an idea about post loop. If you have any queries or suggestions, please feel free to comment us. You can subscribe to us at Facebook and Twitter.

Related articles you May also like

Leave a Reply

Your email address will not be published. Required fields are marked *