pre_get_posts for two loops on same page

I'm using two loops on homepage, one is to show the 3 latest posts, and the other one to show the rest of the posts minus the 3 first posts.

I'm using the following code for the pre_get_posts.

function tax_and_offset_homepage( $query ) {
 if ( !is_admin()  $query-is_home()  $query-is_main_query() )
  $query-set( 'post_type', array( 'post') );

$ppp = get_option( 'posts_per_page' );
//$ppp = 300;
$offset = 3;

if ( !$query-is_paged() ) {
  $query-set( 'posts_per_page', $ppp);
        $query-set( 'offset', $offset);

 }
} 
add_action('pre_get_posts','tax_and_offset_homepage');

and the following code for the basic loop:

?php 
 if ( have_posts() ) {
while ( have_posts() ) {
    the_post(); 
    //
    // Post Content here
    //
} // end while
} // end if
?

but the problem is that the pre_get_posts can be applied to one of the 2 loops. How can i have 2 pre_get_posts function for two loops on same page?

Topic pre-get-posts loop Wordpress

Category Web


Have a look at WP_Query when you need to loop through posts.

<?php 
  $args = array( 
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => -1,
    'post__not_in' => array(),
    'order' => 'DESC',
  );
  $the_query = new WP_Query($args);

  // Show the first 3 posts
  while($the_query->have_posts()) { $the_query->the_post(); 
    echo '<h2>'.get_the_title().'</h2>';

    // Have we shown 3 yet? Break then. (current_post counter stats at 0)
    if( $the_query->current_post == 2 ) { break; }
  }

  // Continue the loop where we left off
  while($the_query->have_posts()) { $the_query->the_post(); 
    echo '<h2>'.get_the_title().'</h2>';
  }

  wp_reset_postdata();
?>

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.