WordPress.org

Ready to get started?Download WordPress

Forums

WP_Query 'posts_per_page' sometimes getting fewer posts than should (4 posts)

  1. DougJoseph
    Member
    Posted 1 year ago #

    The following code is working great, except for an intermittent (seemingly random) glitch: sometimes instead of getting two (2) posts to show, it only gets one (1). ???

    I have verified that the categories have more than 2 posts of the right type in the instances where this is happening. It's not because there are no more posts to be pulled.

    Can anyone think of any possible avenues to check as to why?

    <?php $args = array(
    	'type'                     => 'book',
    	'child_of'                 => 13,
    	'orderby'                  => 'id',
    	'order'                    => 'ASC',
    	'hide_empty'               => 1,
    	'hierarchical'             => 0);
    
    	$cats = get_categories( $args );
    
    	foreach ($cats as $cat):
    			$catID = $cat->term_id;
    			$catName = $cat->name;
    			$catSlug = $cat->slug;
    
    				$args = array(
    				'post_type' => array('books'),
    				'cat' => $catID,
    				'posts_per_page'=> 2,
    				'offset'=>0,
    				'orderby'=>'rand');
    				$wp_query= null;
    				$wp_query = new WP_Query();
    				$wp_query->query($args);
    				?>
                <?php if ( $wp_query->have_posts() ) : ?>
  2. Justin
    Member
    Posted 1 year ago #

    If the problem is random then I would look at the your website speed or hosts first. What plugins are you using?

  3. DougJoseph
    Member
    Posted 1 year ago #

    To offer more clarity:

    As shown, the script iterates through a list of categories.

    When ran (when page is served), it finishes each query, and outputs the page completely. If there were a problem with resources, the page would simply not load. The queries that come back with only 1, instead of 2, are completed queries.

    Regarding plugins: There are no plugins at work in this index page I've written.

    The above is the full code responsible for the query.

    All the categories are immediate children of cat 13, and they have no "child" cats under them.

  4. DougJoseph
    Member
    Posted 1 year ago #

    The 'offending' instances seem to happen most often on the 5th, 7th, and 9th queries (in order). Occasionally these instances will pull two. Usually they pull only one. ???

Topic Closed

This topic has been closed to new replies.

About this Topic