Wordpress Date.php 只返回五个帖子和许多空帖子


Wordpress Date.php returns only five posts and many empty posts

我在wordpress中实现了每月存档,因此使用date.php文件显示每月的帖子。在这个文件中,我有一些分页代码来获取月份和日期,但我的循环只显示五个帖子并包含许多空帖子,如果我进行分页,比如每页 3 个帖子,即使分页有效,总页数仍然是 5。除此之外,结果还包含许多空帖子(我的意思是它没有字段,但the_title返回 1。1979年1月)。

我的循环看起来像这样(没关系外部位 - 这是一个自定义字段,用于确定整个帖子是否存储在外部):

$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
?>

包括分页逻辑在内的整个代码可在此处找到:https://gist.github.com/uansett/fd1183216ab980e1279a#file-date-php

get_posts不会取代WordPress已经为该页面选择的帖子。 你需要类似的东西(未经测试):

$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 ?>

如果做不到这一点,您可以使用query_posts,它确实替换了WordPress选择的帖子。 虽然法典通常建议不要使用query_posts

TL;DR 永远不要使用 query_posts();