Support » Plugins » Hacks » Sticky Posts ignores 'posts_per_page'

  • Hi,
    I am in middle of coding a theme and stuck!!

    This is the code I am using to get the latest posts.

    $args = array( 'posts_per_page'=> 6, 'paged' => $paged );
    		if (have_posts()) : while (have_posts()) : the_post(); ?>
    		<div class="home-widgets">
    			<?php if ( has_post_thumbnail() ) {	the_post_thumbnail('recent');}
    			<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
    			<p><?php echo get_the_content();?></p>
    			<div class="cread"><a href="<?php the_permalink(); ?>">Continue &rarr;</a></div>
    		<?php endwhile; ?>

    Now, when I have sticky posts, the query ignores the ‘posts_per_page’ argument. For example, if I have two sticky posts, the number of displayed posts becomes 8 (where I set the ‘posts_per_page’ to 6).

    I got it partially fixed by adding this code;

    $pagenow = (get_query_var('paged')) ? get_query_var('paged') : 1; if ($pagenow == 1){$count = $num - 1;} else {$num = $count;}
    $args = array( 'posts_per_page'=>$count, 'paged' => $paged );

    That breaks the pagination. It is adding an extra page after the last page which resulting in a “Not Found” posts page.

    So, is there any way of doing it properly?

Viewing 5 replies - 1 through 5 (of 5 total)
  • Is this on the home page?

    Thread Starter Abhik


    Yes, it’s on the homepage (index.php)

    looks like it is..

    anyways, do *not* recreate the main loop do this instead from functions.php

    add_filter('pre_get_posts', 'mytheme_blogpostcount_filter');
    	// Set the posts per page on the home page
    	function mytheme_blogpostcount_filter($query) {
    		if ( $query->is_home() && $query->is_main_query() ) {
    			$query->set('posts_per_page', '6');
    		return $query;

    ^ what this will do is make the MAIN loop for wordpress recognize the posts_per_page properly before the main loop is SQL run that way it gets parsed properly with the pagination and other things…

    You might have to add the filter to init .. i forget.

    function mytheme_blogpostcount_filter_init() {
          add_filter('pre_get_posts', 'mytheme_blogpostcount_filter');

    ^ if someone wants to chime in on whether or not it’s necessary to run in init (or other action location)

    Thread Starter Abhik


    Thanks Frumph,
    Can you please tell me what exactly I need to do after I add this filter from functions.php?
    I mean, how do I get the posts in index.php?

    … you just do the regular if (have_posts()) stuff … just without the query before it

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Sticky Posts ignores 'posts_per_page'’ is closed to new replies.