Skip to content
Advertisement

WordPress: Latest post missing from category feed

I have setup a custom field to pull a specified category ID to display using WP_Query on a page’s side bar. It pulls the posts in the correct category, but skips the most recent one. Here is the snip of code:

<?php
    $catID = get_field ( 'category_id_posts' );
    $catquery = new WP_Query( 'cat='. $catID .'&posts_per_page=5' );
    ?>
    <?php if($catquery->have_posts()) : $catquery->the_post(); ?>
    <div id="recent-posts-2">       
        <h3 class="widget-title">Recent Posts</h3>
        <ul class="nav flex-column">
            <?php while($catquery->have_posts()) : $catquery->the_post(); ?>
            <li class="nav-item">
                <a class="nav-link" href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a>
            </li>
            <?php endwhile; ?>
        </ul>
    </div>
    <?php
    endif;
    wp_reset_postdata(); ?>

Even when I simplify the WP_Query and remove the variable like this:

$catquery = new WP_Query( 'cat=7&posts_per_page=5' );

It still skips over the latest post within that category.

Any insight would be greatly appreciated, thank you!

Advertisement

Answer

you need to check if $catquery->have_posts() for example –

<?php if ( $catquery->have_posts() ) : ?>

<?php while ( $catquery->have_posts() ) : $catquery->the_post(); ?>
..
..
..
..
<?php endwhile; ?>
<?php endif;
  wp_reset_postdata(); 
?>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement