query_posts() is a WordPress function that is used to retrieve and display posts from the database. It can be used multiple times on a single page, but it’s not recommended as it can cause performance issues. It is recommended to use WP_Query() class instead, which is more efficient and flexible.

Here’s an example of how you could use query_posts() twice on a single page to display two different sets of posts:

<?php
// First query to retrieve and display posts from the 'news' category
query_posts( 'category_name=news' );
if ( have_posts() ) {
    while ( have_posts() ) {
        the_post();
        echo '<h2>' . get_the_title() . '</h2>';
        echo '<p>' . get_the_excerpt() . '</p>';
    }
}

// Second query to retrieve and display posts from the 'events' category
query_posts( 'category_name=events' );
if ( have_posts() ) {
    while ( have_posts() ) {
        the_post();
        echo '<h2>' . get_the_title() . '</h2>';
        echo '<p>' . get_the_excerpt() . '</p>';
    }
}
?>

This example will retrieve and display all the posts from the ‘news’ category first and then all the posts from the ‘events’ category.

It’s important to note that using query_posts() multiple times on a single page will overwrite the original query and can cause unexpected results. It’s also important to reset the query using wp_reset_query() after query_posts() is used.

<?php
// First query to retrieve and display posts from the 'news' category
query_posts( 'category_name=news' );
if ( have_posts() ) {
    while ( have_posts() ) {
        the_post();
        echo '<h2>' . get_the_title() . '</h2>';
        echo '<p>' . get_the_excerpt() . '</p>';
    }
}
wp_reset_query();

// Second query to retrieve and display posts from the 'events' category
query_posts( 'category_name=events' );
if ( have_posts() ) {
    while ( have_posts() ) {
        the_post();
        echo '<h2>' . get_the_title() . '</h2>';
        echo '<p>' . get_the_excerpt() . '</p>';
    }
}
wp_reset_query();
?>

This way you ensure that the original query is restored, so the rest of your page can function correctly.

(Visited 26 times, 1 visits today)
Was this article helpful?
YesNo
Close Search Window