sinanisler logo

Query Post Example for Reading Category

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();

 

  1. The query_posts function alters the main query and should be used with caution. In many cases, it’s better to use WP_Query or get_posts to create custom loops, as they don’t interfere with the main query.
  2. Always reset the query after using query_posts by calling wp_reset_query() to ensure that any subsequent loops behave as expected.
  3. If you intend to use this in a template file (like page.php or single.php), you’d generally avoid putting the loop code in functions.php and instead place it directly in the template file.

Leave the first comment