分享学习记录
互联网技术知识

WordPress利用wp_get_recent_posts函数显示最新文章的教程

最近在使用WordPress时用到wp_get_recent_posts函数,以前一直没用过,今天碰到一个问题,默认情况下,如果根据WordPress给的示例:

<h2>最新文章</h2>
<ul>
<?php
$recent_posts = wp_get_recent_posts();
foreach( $recent_posts as $recent ){
echo '<li><a href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"].'</a> </li> ';
}
wp_reset_query();
?>
</ul>

直接这么用的话,默认会将计划任务文章显示出来,而如果使用WP_Query或query_posts方法就不会出现这种错误。这样显示是有问题的,生产环境必须只能显示已经发布的文章,必须要在参数中指定状态:

<h2>最新发布文章</h2>
<ul>
<?php
$args = array( 'numberposts' => '5','post_status' => 'publish', );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo '<li><a href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"].'</a> </li> ';
}
wp_reset_query();
?>
</ul>

指定post_status参数就行。

赞(0)
文章名称:《WordPress利用wp_get_recent_posts函数显示最新文章的教程》
文章链接:https://www.bailuze.com/15012.html
本站所有文章,如无特殊说明或标注,均为本站原创发布。任何在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
本站专注于百度、搜狗、360、谷歌、bing等常见搜索引擎的优化,关键词排名的提高,诚意咨询邮箱526009505@qq.com
分享到