GeekerCode更好的WordPress主题,值得信任的WordPress主题开发商

极美的主题、极致的插件

WordPress获取最新发表文章函数: wp_get_recent_posts()

摘要:【说明】按发表时间检索数据库中的最新发表文章。默认检索最近十篇文章。【用法】<?php wp_get_recent_posts( $args ) ?>【参数】<?php$args = array(&

【说明】

按发表时间检索数据库中的最新发表文章。默认检索最近十篇文章。

【用法】

<?php wp_get_recent_posts( $args ) ?>

【参数】

<?php
$args = array(
    'numberposts' => 10,
    'offset' => 0,
    'category' => 0,
    'orderby' => 'post_date',
    'order' => 'DESC',
    'include' => ,
    'exclude' => ,
    'meta_key' => ,
    'meta_value' =>,
    'post_type' => 'post',
    'post_status' => 'draft, publish, future, pending, private',
    'suppress_filters' => true
    );
?>

或者传入一个(整数)将获取的文章数量

默认值: 10

【返回的值】(数组) 跟 get_posts 不同get_posts 返回的是 objects 文章列表

【示例】

1.返回最新的10篇文章

<h2>Recent Posts</h2>
<ul>
<?php
$recent_posts = wp_get_recent_posts();
foreach( $recent_posts as $recent ){
    echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' .   $recent["post_title"].'</a> </li> ';
 }
?>
</ul>

2.返回最新的5篇文章

<h2>Recent Posts</h2>
<ul>
<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
    echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' .   $recent["post_title"].'</a> </li> ';
}
?>
</ul>

【修改记录】自1.1.0版本后

【源文件】wp_get_recent_posts() is located in wp-includes/post.php.

/**
 * Retrieve number of recent posts.
 *
 * @since 1.0.0
 * @uses wp_parse_args()
 * @uses get_posts()
 *
 * @param string $deprecated Deprecated.
 * @param array $args Optional. Overrides defaults.
 * @param string $output Optional.
 * @return unknown.
 */
function wp_get_recent_posts( $args = array(), $output = ARRAY_A ) {
 
 if ( is_numeric( $args ) ) {
  _deprecated_argument( __FUNCTION__, '3.1', __( 'Passing an integer number of posts is deprecated. Pass an array of arguments instead.' ) );
  $args = array( 'numberposts' => absint( $args ) );
 }
 
 // Set default arguments
 $defaults = array(
  'numberposts' => 10, 'offset' => 0,
  'category' => 0, 'orderby' => 'post_date',
  'order' => 'DESC', 'include' => '',
  'exclude' => '', 'meta_key' => '',
  'meta_value' =>'', 'post_type' => 'post', 'post_status' => 'draft, publish, future, pending, private',
  'suppress_filters' => true
 );
 
 $r = wp_parse_args( $args, $defaults );
 
 $results = get_posts( $r );
 
 // Backward compatibility. Prior to 3.1 expected posts to be returned in array
 if ( ARRAY_A == $output ){
  foreach( $results as $key => $result ) {
   $results[$key] = get_object_vars( $result );
  }
  return $results ? $results : array();
 }
 
 return $results ? $results : false;
}

建站!你有充足的理由选择我们

世界上超过30%的网站是由WordPress搭建,而我们是国内最靠谱的WordPress主题开发商
QQ咨询在线咨询问答互助微信号geekercode微信公众号云服务器