Thursday, February 6, 2014

Showing less posts on front page of Wordpress site



Today I spent lot of time on exploring various options for showing less number of posts on front page of Motivational Quotes site TheQuotes.net.

We can set the number of posts per page from admin panel of wordpress site. But we can not set separate number of posts per page for the home page.

Home page of TheQuotes.Net is showing Image quote also apart from showing summary of recent blog posts. So, I wanted to show less number of posts on home page. i-e 4 posts on home page while showing 12 posts per page on other paginated pages.

I tried various approaches. But each approach was having some shortcomings. Finally the below approach/code worked fine.

I added below peace of code into the functions.php of our theme.

function sfppc_posts_filter( &$query ) {
if ( $query != $GLOBALS['wp_the_query'] || !$query->is_home )
return;

$posts_per_page = $query->get('posts_per_page') ? $query->get('posts_per_page') : get_option('posts_per_page');

if ( $query->is_paged )
$query->set( 'offset', ($query->get('paged') - 2) * $posts_per_page + 4 );
else
$query->set( 'posts_per_page', 4 );
}
add_action( 'pre_get_posts', 'sfppc_posts_filter' );


It worked fine. But the home page pagination part was having links for some additional pages also. i-e It prepared the pagination links based on the first page posts i-e "4 posts per page"

So, I just added below piece of code before calling pagination code.

global $query_string;
query_posts( $query_string . '&posts_per_page=12' );

Now, everything is working fine. i-e 4 posts on home page and 12 posts on other pages (e.g 2nd page). Let me know if you still find any issue in TheQuotes.Net



You can subscribe to our Email posts, and you can bookmark this blog for further reading, or you can subscribe to our blog feed.

No comments:

Search This Blog