你可以利用WP_Query 调用类别中的最新帖子并显示它。看看category parameters. 默认情况下,WP_Query 使用post 由于按发布日期发布的发布类型和订单,因此我们可以将其从查询中排除。如果你需要其他东西,你可以在你的论点中定义它们
你基本上可以试试这样的
$args = array(
\'posts_per_page\' => 1, // we need only the latest post, so get that post only
\'cat\' => \'ID OF THE CATEGORY\', // Use the category id, can also replace with category_name which uses category slug
//\'category_name\' => \'SLUG OF FOO CATEGORY,
);
$q = new WP_Query( $args);
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
//Your template tags and markup like:
the_title();
}
wp_reset_postdata();
}
这应该为您提供一个基础,您可以根据需要修改、自定义和使用它。如果您不确定参数和用法,请查看
WP_Query codex page 寻求帮助
编辑我真的不知道你为什么决定重新发明轮子get_posts 我向您展示了一个如何使用WP_Query. 您对的使用get_posts 结合WP_Post 属性完全错误
在WP_Post 属性是未过滤的,因此此操作的输出是完全未过滤的,并且看起来与模板标记的输出不同,如the_title() 或the_content(). 必须对这些属性使用适当的过滤器
title 和content 的属性无效WP_POST. 另一个答案是完全错误的。是的post_title 和post_content只需使用setup_postdata( $post ); 然后使用wp_reset_postdata() 之后
您可以尝试以下方法
function latest_post() {
$args = array(
\'posts_per_page\' => 1, // we need only the latest post, so get that post only
\'cat\' => \'4\' // Use the category id, can also replace with category_name which uses category slug
);
$str = "";
$posts = get_posts($args);
foreach($posts as $post):
$str = $str."<h2>". apply_filters( \'the_title\', $post->post_title) ."</h2>";
$str = $str."<p class=\'post-content-custom\'>". apply_filters( \'the_content\', $post->post_content ) ."</p>";
endforeach;
return $str;
}
add_shortcode(\'latest_post\', \'latest_post\');