Wordpress Custom Loop不显示任何帖子

时间:2015-09-14 20:53:13

标签: php wordpress

我正在尝试添加自定义循环以显示类别主页中的帖子标题。这是我到目前为止的代码,但它没有显示任何帖子。顺便说一下,我在single.php中使用这段代码。

<?php $recentPosts = new WP_Query(); ?>
<?php if ( $recentPosts->have_posts() ) : ?>
    <?php $recentPosts->query_posts( array ( 'category_name' => 'homepage', 'posts_per_page' => 10 ) ); ?>
           <?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
    <?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_postdata(); ?>

我不太确定发生了什么,但我会感激任何帮助。

1 个答案:

答案 0 :(得分:2)

您正在对查询对象进行大量不必要的处理。由于您正在处理存档页面,因此您应该能够创建一个名为 category-homepage.php 的新模板文件(假设该类别的slug为homepage)。在其中,您可以放置​​以下内容:

$args = array(
    'category_name' => 'homepage', 
    'posts_per_page' => 10
);
$recentPosts = new WP_Query( $args );
if ( $recentPosts->have_posts() ) : 
    while ( $recentPosts->have_posts() ) : $recentPosts->the_post(); ?>

    <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>

<?php endwhile; endif; ?>

同样,因为它是一个类别存档页面,所以你不应该对 single.php 做任何事情。您可以阅读有关模板层次结构in the Codex的更多信息。

相关问题