钩子文档

posts_results

💡 云策文档标注

概述

posts_results 是一个 WordPress 过滤器钩子,用于在状态检查之前过滤原始的帖子结果数组。它允许开发者在 WP_Query 返回帖子对象数组后、进行进一步处理前修改这些结果。

关键要点

  • 过滤器名称:posts_results
  • 参数:$posts(WP_Post 对象数组)和 $query(WP_Query 实例,通过引用传递)
  • 应用场景:在 WP_Query::get_posts() 中调用,用于自定义帖子筛选逻辑
  • 引入版本:WordPress 2.3.0

代码示例

add_filter( 'posts_results', 'my_posts_results_filter' );

function my_posts_results_filter( $posts ) {
    $filtered_posts = array();
    print_r( $posts );
    foreach ( $posts as $post ) {
        if ( false === strpos($post->post_title, 'selfie')) {
            // safe to add non-selfie title post to array
            $filtered_posts[] = $post;
        }
    }
    return $filtered_posts ;
}

📄 原文内容

Filters the raw post results array, prior to status checks.

Parameters

$postsWP_Post[]
Array of post objects.
$queryWP_Query
The WP_Query instance (passed by reference).

More Information

The input of this filter is an array of posts, created by any(?) WP_Query looking for posts.

Source

$this->posts = apply_filters_ref_array( 'posts_results', array( $this->posts, &$this ) );

Changelog

Version Description
2.3.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Example migrated from Codex:

    Code sample for filtering an array of posts results and return an array of post objects which does not have the word “selfie” in the title.

    add_filter( 'posts_results', 'my_posts_results_filter' );
    
    function my_posts_results_filter( $posts ) {
    	$filtered_posts = array();
    	print_r( $posts );
    	foreach ( $posts as $post ) {
    		if ( false === strpos($post->post_title, 'selfie')) {
    			// safe to add non-selfie title post to array
    			$filtered_posts[] = $post;
    		}
    	}
    	return $filtered_posts ;
    }