You might use the query_posts
function in a WordPress index.php or page.php or single.php
file. or where ever you want 🙂
The following code creates a custom WordPress loop to query the latest 5 posts from the “news” category;
// Add this to your theme's functions.php file function custom_news_loop() { // The Query query_posts( array( 'category_name' => 'news', // Use the category slug 'posts_per_page' => 5 )); // The Loop if ( have_posts() ) { echo '<ul>'; while ( have_posts() ) { the_post(); echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>'; } echo '</ul>'; } else { echo 'No news posts found'; } // Reset Query wp_reset_query(); } // To use the function in your theme, just call it: custom_news_loop();
- The
query_posts
function alters the main query and should be used with caution. In many cases, it’s better to useWP_Query
orget_posts
to create custom loops, as they don’t interfere with the main query. - Always reset the query after using
query_posts
by callingwp_reset_query()
to ensure that any subsequent loops behave as expected. - If you intend to use this in a template file (like
page.php
orsingle.php
), you’d generally avoid putting the loop code infunctions.php
and instead place it directly in the template file.