In WordPress, the Loop is used to display a set of posts on a page. The default Loop displays the latest posts on the homepage, but you can also create custom Loops to display specific sets of posts based on different criteria. Here’s an example of how to write a custom Loop in WordPress:
- In your template file, create a new query using the
WP_Queryclass allows you to retrieve posts based on different parameters such as the post type, category, tag, author, and more.
<?php $custom_query = new WP_Query( array( 'post_type' => 'post', 'category_name' => 'news', 'posts_per_page' => 10, 'orderby' => 'date', 'order' => 'ASC' ) ); ?>
- Create a new Loop using the
whilestatement, and use the
the_post()functions to check for and set up the current post.
<?php if ( $custom_query->have_posts() ) : while ( $custom_query->have_posts() ) : $custom_query->the_post(); ?>
- Inside the Loop, use template tags such as
the_permalink()to display the post’s title, content, and permalink.
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <?php the_content(); ?>
- Close the Loop using the
<?php endwhile; wp_reset_postdata(); endif; ?>
- Remember to reset the post data using
wp_reset_postdata()function after the loop, this is important so that the global
$postvariable is restored to the current post in the main query.
By following these steps, you can create a custom Loop in WordPress that displays a specific set of posts based on the parameters you set in the
WP_Query class. You can also use other query functions like
query_posts() to create custom loop but it’s not recommended to use
query_posts() as it modifies the main query of the page, which could lead to unexpected results.
It is important to note that it’s best practice to use the
WP_Query class to create custom loops, as it doesn’t modify the main query and it’s more efficient.
Last modified: January 16, 2023