wp_filter_object_list()
云策文档标注
概述
wp_filter_object_list() 函数用于基于一组键值对参数过滤对象列表,返回匹配的对象或指定字段。它扩展了 wp_list_filter() 的功能,支持通过 $field 参数提取特定字段。
关键要点
- 函数基于 key => value 参数过滤对象数组,key 对应属性名,value 对应属性值。
- 支持 AND、OR、NOT 三种逻辑操作符,AND 要求所有参数匹配,OR 只需一个匹配,NOT 要求无参数匹配。
- 通过 $field 参数可提取匹配对象的特定字段,而非整个对象。
- 内部使用 WP_List_Util 类实现,自 WordPress 4.7.0 起重构。
代码示例
$pages = wp_filter_object_list( $wp_query->posts, array(
'post_type' => 'page'
) );
原文内容
Filters a list of objects, based on a set of key => value arguments.
Description
Retrieves the objects from the list that match the given arguments.
Key represents property name, and value represents property value.
If an object has more properties than those specified in arguments, that will not disqualify it. When using the ‘AND’ operator, any missing properties will disqualify it.
When using the $field argument, this function can also retrieve a particular field from all matching objects, whereas wp_list_filter() only does the filtering.
Parameters
$input_listarrayrequired-
An array of objects to filter.
$argsarrayoptional-
An array of key => value arguments to match against each object.
Default:
array() $operatorstringoptional-
The logical operation to perform.
'AND'means all elements from the array must match.'OR'means only one element needs to match.'NOT'means no elements may match. Default'AND'. $fieldbool|stringoptional-
A field from the object to place instead of the entire object.
Default:
false
Source
function wp_filter_object_list( $input_list, $args = array(), $operator = 'and', $field = false ) {
if ( ! is_array( $input_list ) ) {
return array();
}
$util = new WP_List_Util( $input_list );
$util->filter( $args, $operator );
if ( $field ) {
$util->pluck( $field );
}
return $util->get_output();
}
Skip to note 2 content
Codex
Filtering out certain post types from the loop following a search
If multiple post types are returned in a search query you can filter out the posts that are of post type ‘page’ only.
$pages = wp_filter_object_list( $wp_query->posts, array( 'post_type' => 'page' ) );