I am implementing a monthly archive in wordpress, and so am using the date.php file to display posts per month. In this file I have some paging code to get the month and date, but my Loop only ever displays five posts and includes many empty posts, if I do paging, with say 3 posts per page, the total pages is still 5 even though the paging works. In addition to this, the result contains many empty posts (by which I mean it has no fields, but the_title returns 1. January 1979).
My loop looks like this (nevermind the external bit - its a custom field to determine if the whole post is stored externally):
$current_page = max(1, get_query_var('paged'));
$posts = get_posts('cat=19,20&posts_per_page=3&monthnum='.$m.'&year='.$y.'&paged='.$current_page);
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
//
// Post Content here
?>
<?php $externalLink = do_shortcode('[cft key=external before_list="" after_list="" before_value="" after_value=""]'); ?>
<?php if( strlen($externalLink) <= 1): ?>
<div class="title">
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
<div class="time small">
<?php if(get_the_time('Y') != '1970') the_time('F jS, Y'); //the_category('','multiple'); ?>
</div>
</div>
<?php else: ?>
<div class="title">
<a href="<?php echo $externalLink ?>" target="_blank" rel="bookmark" title="External Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
<div class="time small">
<?php if(get_the_time('Y') != '1970') the_time('F jS, Y'); // the_category('','multiple');?>
</div>
</div>
<?php endif; ?>
<?php
} // end while
} // end if
?>
The whole code including the paging logic is found here: https://gist.github.com/uansett/fd1183216ab980e1279a#file-date-php
get_posts
doesn't replace the posts WordPress has already selected for the page. You'd need something like (untested):
$posts = get_posts('cat=19,20&posts_per_page=3&monthnum='.$m.'&year='.$y.'&paged='.$current_page);
foreach ( $posts as $post ) : setup_postdata( $post ); ?>
// Your code
<?php endforeach;
wp_reset_postdata(); // If you still want to access the originally selected posts ?>
Failing that you could use query_posts
, which does replace the posts WordPress has selected. Though the codex generally advises against using query_posts
:
TL;DR don't use query_posts() ever;