简体   繁体   English

WordPress自定义循环不显示任何帖子

[英]Wordpress Custom Loop doesn't show any posts

I'm trying to add a custom loop to display post titles from the category homepage. 我试图添加一个自定义循环以显示类别主页上的帖子标题。 Here's the code I have so far so, but it's not displaying any posts. 这是到目前为止的代码,但未显示任何帖子。 BTW, I'm using this code in single.php. 顺便说一句,我在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(); ?>

I'm not too sure what's going on, but would appreciate any help I can get. 我不太确定这是怎么回事,但是希望能得到我的帮助。

You're doing a lot of unnecessary messing around with your query object. 您正在对查询对象进行很多不必要的处理。 Since you're dealing with an archive page, you should be able to create a new template file called category-homepage.php (assuming the slug of the category is homepage ). 由于您要处理的是存档页面,因此您应该能够创建一个名为category-homepage.php的新模板文件(假设类别的标签是homepage )。 In it, you could place something like the following: 在其中,您可以放置​​以下内容:

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

Again, since it's a category archive page, you shouldn't be doing anything to single.php . 同样,由于它是类别归档页面,因此您不应该对single.php做任何事情。 You can read more about template hierarchy in the Codex . 您可以在Codex中阅读有关模板层次结构的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM