Search code examples
wordpressposts

How to have one query, but use it twice on a page in two seperate HTML blocks to display different posts


On my homepage, I currently have a featured post at the top. Then later in the page, I display the next four newest posts using offset 1 to not show the featured post.

I'm currently using two queries using the following code;

<?php $query = new WP_Query( array(
        'post_type' => array('post'),
        'posts_per_page' => 1
    ) );
    ?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
   /*Show post info here*/
<?php endwhile; ?>

I then have a second brand new query further down the page, doing the same thing, but calling the next 4 posts.

<?php $query = new WP_Query( array(
        'post_type' => array('post'),
        'posts_per_page' => 4,
            'offset' => 1,
    ) );
    ?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
   /*Show post info here*/
<?php endwhile; ?>

Is there a way to make the query once, but still output the results into two seperate HTML blocks?


Solution

  • You could use a unique query using WordPress get_posts() function like:

    <?php 
    // The unique query for 5 posts
    $posts = get_posts( array(
        'post_type'   => array('post'),
        'numberposts' => 5
    ) ); ?>
    
    <?php // First block (1st post)
    if ( $posts ) {
        $post = reset($posts); // Get the first post (WP_Post object)
    
        // Display the post title (and the post ID) for example
        echo $post->post_title . ' (' . $post->ID . ')<br>'; 
    } ?>
    
    <?php // Second block (other 4 posts)
    if ( count($posts) > 2 ) {
        // Loop through posts (WP_Post objects)
        foreach( $posts as $key => $post ) {
            // Bypass the first post
            if ( $key > 0 ) {
                // Display the post title (and the post ID) for example
                echo $post->post_title . ' (' . $post->ID . ')<br>';
            }
        }
    } ?>
    

    It should work.