Last active
August 29, 2015 14:23
-
-
Save uprise10/e5350edf222c21430729 to your computer and use it in GitHub Desktop.
WordPress: custom number of posts for homepage only
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* This piece of code let you use a different number of posts for the homepage, than the default posts_per_page setting. | |
*/ | |
add_action( 'pre_get_posts', 'yourprefix_filter_posts' ); | |
add_filter('found_posts', 'yourprefix_adjust_offset_pagination', 1, 2 ); | |
$posts_on_homepage = 7; // Custom number of posts for the homepage | |
$default_per_page = get_option('posts_per_page'); | |
/** | |
* Alters the nuber of posts for the homepage | |
*/ | |
function yourprefix_filter_posts( $query ) { | |
if( is_admin() || false == $query->is_main_query() ) { | |
return; | |
} | |
if( false == $query->is_paged ) { | |
$query->set( 'posts_per_page', $posts_on_homepage ); | |
} | |
else { | |
$page_offset = ( ( $query->query_vars['paged'] - 1 ) * $default_per_page ) - ( $default_per_page - $posts_on_homepage ); | |
$query->set('offset', $page_offset ); | |
} | |
} | |
/** | |
* Alters the found_posts veriable, so the pagination will not break. | |
*/ | |
function yourprefix_adjust_offset_pagination( $found_posts, $query ) { | |
if( is_admin() || false == $query->is_main_query() ) { | |
return; | |
} | |
// Define the homepage offset... | |
$found_posts = ( $found_posts - $posts_on_homepage ) + $default_per_page; | |
return $found_posts; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment