我想在我的Wordpress自定义主页上做一个小的"最新消息"部分,输出:
- 2个最新新闻 <
- 名称/gh>
- 摘录
我试着从法典中取出标准循环,看看我先得到什么,但我什么也没得到。我有点困惑,因为我不能弄清楚为什么它甚至不输出任何帖子,根本没有使用基本循环的内容:
<?php
// The Query
$the_query = new WP_Query( 'post_count=2' );
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
} else {
// no posts found
echo 'No news is good news!';
}
/* Restore original Post Data */
wp_reset_postdata();
?>
这段代码目前显示"没有消息就是好消息"消息。
你的代码在我这边渲染输出,所以它是工作的。你有一个问题,post_count
是一个属性,而不是WP_Query
的参数。你应该使用posts_per_page
我相信为什么你没有得到任何输出,是因为你使用的是自定义的帖子类型,而不是正常的帖子,在这种情况下,由于你没有任何正常的帖子,因此不会呈现任何输出。
修改这一行
$the_query = new WP_Query( 'post_count=2' );
$the_query = new WP_Query( 'posts_per_page=2&post_type=NAME_OF_POST_TYPE' );
您将变量$args传递给WP_Query,但实际上没有定义它。
试试这个:
$args = array(
'post_type' => 'post',
'posts_per_page' => 2,
'no_found_rows' => false,
);
$the_query = new WP_Query( $args );
然后输出你需要的内容:
if ( $the_query->have_posts() ) :
echo '<ul>';
while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<?php the_excerpt(); ?>
</li>
<?php endwhile;
echo '</ul>';
else :
// no posts found
echo 'No news is good news!';
endif;
wp_reset_postdata();
对于if语句,您不需要使用这种替代语法,但通常会看到这样写。
我注意到自从写这个答案以来,你更新了你在'post_count=2'
传递给WP_Query的问题。您需要使用'posts_per_page'
代替。post_count
是查询对象的属性,不是参数
这应该只返回最近发布的两篇文章。
<?php
$args=array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 2,
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() )
{
echo '<ul>';
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li>
<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
<?php the_excerpt(); ?>
</li>
<?php endwhile;
echo '</ul>';
<?php
}
else
{
echo 'No news is good news!';
}
wp_reset_query(); // Restore global post data stomped by the_post().
?>
(以上内容与本文略有不同)