I think I’ve understood your question, and I hope this can help.
To display a hero section with the most recent posts without interfering with the main loop and pagination, you can use a combination of WP_Query
for the hero section and pre_get_posts()
to modify the main query. Here’s the code to achieve this:
// Section 1 - Hero Section
$hero_args = array(
'posts_per_page' => 5, // Number of posts to display in the hero section
// Add any other query parameters you need for the hero section
);
$hero_query = new WP_Query( $hero_args );
// Create an array to store the post IDs from the hero section
$hero_post_ids = array();
if ( $hero_query->have_posts() ) :
while ( $hero_query->have_posts() ) :
$hero_query->the_post();
// Display content for the hero section here
$hero_post_ids[] = get_the_ID(); // Store the post ID
endwhile;
wp_reset_postdata(); // Reset the hero section query
endif;
// Function to modify the main query
function modify_main_query( $query ) {
if ( is_home() || is_archive() && $query->is_main_query() ) {
// Exclude posts from the hero section
$query->set( 'post__not_in', $hero_post_ids );
}
}
add_action( 'pre_get_posts', 'modify_main_query' );
// Section 2 - Regular Loop
while ( have_posts() ) :
the_post();
// Display content for the regular loop here
endwhile;
// Pagination for the regular loop
the_posts_pagination();
This code creates a separate WP_Query
for the hero section, displays its content, and then modifies the main query using pre_get_posts
to exclude the post IDs from the hero section, ensuring that they won’t appear in the main loop. This approach maintains proper pagination and prevents duplicate posts between the hero section and the main loop.