amberweinberg

Offset Main WordPress Loop Without Messing Up Pagination

Oct 18th, 2017
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.51 KB | None | 0 0
  1. // ******************* Custom Blog Offset ****************** //
  2.  
  3. add_action('pre_get_posts', 'myprefix_query_offset', 1 );
  4. function myprefix_query_offset(&$query) {
  5.    
  6.     global $wp_the_query;
  7.  
  8.     //Before anything else, make sure this is the right query...
  9.     if ( ! $query->is_home() ) {
  10.         return;
  11.     }
  12.    
  13.     if($wp_the_query === $query) {
  14.  
  15.         //First, define your desired offset...
  16.         $offset = 1;
  17.        
  18.         //Next, determine how many posts per page you want (we'll use WordPress's settings)
  19.         $ppp = get_option('posts_per_page');
  20.    
  21.         //Next, detect and handle pagination...
  22.         if ( $query->is_paged ) {
  23.    
  24.             //Manually determine page query offset (offset + current page (minus one) x posts per page)
  25.             $page_offset = $offset + ( ($query->query_vars['paged']-1) * $ppp );
  26.    
  27.             //Apply adjust page offset
  28.             $query->set('offset', $page_offset );
  29.    
  30.         }
  31.         else {
  32.    
  33.             //This is the first page. Just use the offset...
  34.             $query->set('offset',$offset);
  35.    
  36.         }
  37.      }
  38. }
  39.  
  40. add_filter('found_posts', 'myprefix_adjust_offset_pagination', 1, 2 );
  41. function myprefix_adjust_offset_pagination($found_posts, $query) {
  42.    
  43.     global $wp_the_query;
  44.  
  45.     //Define our offset again...
  46.     $offset = 1;
  47.  
  48.     //Ensure we're modifying the right query object...
  49.     if ( $query->is_home() && $wp_the_query === $query) {
  50.         //Reduce WordPress's found_posts count by the offset...
  51.         return $found_posts - $offset;
  52.     }
  53.     return $found_posts;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment