钩子文档

widget_posts_args

💡 云策文档标注

概述

widget_posts_args 是一个 WordPress 过滤器,用于修改 Recent Posts 小部件查询文章时的参数。开发者可以通过此 Hook 自定义查询条件,如分类、排序等。

关键要点

  • 过滤器名称:widget_posts_args
  • 参数:$args(数组,WP_Query 参数)和 $instance(数组,当前小部件设置)
  • 用途:允许开发者调整 Recent Posts 小部件的文章查询逻辑
  • 兼容性:从 WordPress 3.4.0 引入,4.9.0 添加 $instance 参数

代码示例

// 按分类名过滤 Recent Posts 小部件
function myorg_recentposts_events($args, $instance) {
    $args['category_name'] = 'upcoming-events';
    return $args;
}
add_filter('widget_posts_args', 'myorg_recentposts_events', 1, 2);

注意事项

  • 过滤器函数必须返回修改后的 $args 数组,否则可能无效
  • 可以使用任何 WP_Query 参数来定制查询
  • 建议将代码添加到主题的 functions.php 文件中

📄 原文内容

Filters the arguments for the Recent Posts widget.

Description

See also

Parameters

$argsarray
An array of arguments used to retrieve the recent posts.
$instancearray
Array of settings for the current widget.

More Information

Use any of the WP_Query parameters for $args.

Source

apply_filters(
	'widget_posts_args',
	array(
		'posts_per_page'      => $number,
		'no_found_rows'       => true,
		'post_status'         => 'publish',
		'ignore_sticky_posts' => true,
	),
	$instance
)

Changelog

Version Description
4.9.0 Added the $instance parameter.
3.4.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    Adding to my custom theme in functions.php:

    //filter recent posts widgets by category name
    function myorg_recentposts_events($args, $instance) {
    	$args['category_name'] = 'upcoming-events';
    	return $args;
    }
    add_filter('widget_posts_args', 'myorg_recentposts_events', 1, 2);

    Most important, return $args!! Spent an hour trying to figure out why my filter wasn’t working.

  2. Skip to note 4 content

    Example migrated from Codex:

    Use the following to sort recent posts of the widget by date. Add the code to the functions.php file of the child theme.

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