函数文档

wp_get_recent_posts()

💡 云策文档标注

概述

wp_get_recent_posts() 函数用于检索指定数量的最新文章,基于 get_posts() 实现,支持自定义参数和输出格式。

关键要点

  • 函数接受两个参数:$args(数组,可选,用于指定检索条件,默认为空数组)和 $output(字符串,可选,指定返回类型为 OBJECT 或 ARRAY_A,默认为 ARRAY_A)。
  • 返回值为数组或 false:成功时返回文章数组,元素类型由 $output 决定;失败时返回空数组。
  • 默认参数包括 numberposts(10)、orderby(post_date)、post_type(post)等,可通过 $args 覆盖。
  • 向后兼容性:当 $output 为 ARRAY_A 时,返回关联数组以兼容 WordPress 3.1 以下版本;其他值返回对象数组。
  • 函数内部处理了过时的整数参数用法,并调用 wp_parse_args() 合并默认参数。

代码示例

// 示例1:检索最近5篇已发布文章
$args = array('numberposts' => 5, 'post_status' => 'publish');
$recent_posts = wp_get_recent_posts($args);

// 示例2:使用 OBJECT 输出类型以匹配 get_posts() 行为
$recent_posts = wp_get_recent_posts($args, OBJECT);

// 示例3:排除特定文章格式
$args = array(
    'numberposts' => 5,
    'tax_query' => array(
        array(
            'taxonomy' => 'post_format',
            'field' => 'slug',
            'terms' => 'post-format-aside',
            'operator' => 'NOT IN'
        )
    )
);
$recent_posts = wp_get_recent_posts($args);

注意事项

  • 在 PHP 7.4 及以上版本中,函数源代码中的 return $results ? $results : false; 可能导致问题,建议使用括号包裹:return ($results ? $results : false);。
  • 函数本身无过滤器,但 Recent Posts Widget 提供了 widget_posts_args 钩子用于参数过滤。
  • 输出类型仅检查 ARRAY_A 常量,其他值均返回对象数组。

📄 原文内容

Retrieves a number of recent posts.

Description

See also

Parameters

$argsarrayoptional
Arguments to retrieve posts.

Default:array()

$outputstringoptional
The required return type. One of OBJECT or ARRAY_A, which correspond to a WP_Post object or an associative array, respectively.

Default:ARRAY_A

Return

array|false Array of recent posts, where the type of each element is determined by the $output parameter. Empty array on failure.

More Information

Only the value of ARRAY_A is checked for $output. Any other value or constant passed will return an array of objects.

This function returns posts in an associative array (ARRAY_A) format which is compatible with WordPress versions below 3.1.

To get output similar to get_posts() , use OBJECT as the second parameter: wp_get_recent_posts( $args, OBJECT );

Source

function wp_get_recent_posts( $args = array(), $output = ARRAY_A ) {

	if ( is_numeric( $args ) ) {
		_deprecated_argument( __FUNCTION__, '3.1.0', __( '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,
	);

	$parsed_args = wp_parse_args( $args, $defaults );

	$results = get_posts( $parsed_args );

	// 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;
}

Changelog

Version Description
1.0.0 Introduced.

User Contributed Notes

  1. Skip to note 7 content

    Limited recent posts thumbnails with captions

    This example can be used to show a limited number of recent posts thumbnails in a slider with captions.
    Sliders uses ids and/or classes on div tags and/or ul tags to apply the custom css and hook up the slideshow in js.
    In this example, we will be using directly the ul tag.

    <ul id="slider-id" class="slider-class">
    	 4, // Number of recent posts thumbnails to display
    		'post_status' => 'publish' // Show only the published posts
    	));
    	foreach( $recent_posts as $post_item ) : ?>
    		<li>
    			<a href="<?php echo get_permalink($post_item['ID']) ?>">
    				
    				//Assuming that the slider support captions 
    				<p class="slider-caption-class"></p>
    			</a>
    		</li>
    	
    </ul>

  2. Skip to note 8 content

    Argument Filering Hook For Widgets

    This function doesn’t have filters but in the default Recent Posts Widget there’s a hook that allows you filter the arguments.

    function filter_recent_posts_widget_parameters( $params ) {
       $params['orderby'] = 'date';
       
       return $params;
    }
    add_filter( 'widget_posts_args', 'filter_recent_posts_widget_parameters' );

  3. Skip to note 10 content

    List the 10 most-recent posts
    This is an example that shows how to use the wp_get_recent_posts() function to list the recent 10 posts.

    <h2>Recent Posts</h2>
    <ul>
    <a href="%1$s">%2$s</a></li>',
    			esc_url( get_permalink( $recent['ID'] ) ),
    			apply_filters( 'the_title', $recent['post_title'], $recent['ID'] )
    		);
    	}
    ?>
    </ul>

  4. Skip to note 11 content

    Limit number of recent posts

    If you want to delimit more or less recent posts you have to put the number in the function parameter like this example below:

    <h2>Recent Posts</h2>
    <ul>
     '5' );
    	$recent_posts = wp_get_recent_posts( $args );
    	foreach( $recent_posts as $recent ){
    		printf( '<li><a href="%1$s">%2$s</a></li>',
    			 esc_url( get_permalink( $recent['ID'] ) ),
    			 apply_filters( 'the_title', $recent['post_title'], $recent['ID'] )
    		 );
    	}
    ?>
    </ul>

  5. Skip to note 12 content

    Exclude posts of a specific post format

    To exclude posts with a certain post format, you can use Class_Reference/WP_Query#Taxonomy_Parameters like this next example, which excludes all posts with the ‘aside’ and ‘image’ formats:

    <h2>Recent Posts</h2>
    <ul>
     '5', 'tax_query' => array(
    		array(
    			'taxonomy' => 'post_format',
    			'field'    => 'slug',
    			'terms'    => 'post-format-aside',
    			'operator' => 'NOT IN'
    		), 
    		array(
    			'taxonomy' => 'post_format',
    			'field'    => 'slug',
    			'terms'    => 'post-format-image',
    			'operator' => 'NOT IN'
    		)
    	) );
    	$recent_posts = wp_get_recent_posts( $args );
    
    	foreach( $recent_posts as $recent ){
    		printf( '<li><a href=%1$s">%2$s</a></li>',
    			esc_url( get_permalink( $recent['ID'] ) ),
    			apply_filters( 'the_title', $recent['post_title'], $recent['ID'] )
    		);
    	}
    ?>
    </ul>