Using WordPress ‘posts_results’ PHP filter

posts_results is a WordPress PHP filter that allows you to modify the raw array of post objects before status checks are performed.

Usage

add_filter( 'posts_results', 'my_posts_results_filter', 10, 2 );
function my_posts_results_filter( $posts, $query ) {
    // Modify the $posts array here
    return $posts;
}

In this example, we’re adding a filter to the ‘posts_results’ hook and specifying a function called ‘my_posts_results_filter’ that will be called when the hook is triggered. The function takes two parameters: the $posts array, which contains the results of the query, and the $query object, which contains information about the query.

Parameters

  • $posts (WP_Post[]): Array of post objects.
  • $query (WP_Query): The WP_Query instance (passed by reference).

Examples

Change Post Titles

function modify_post_titles($posts, $query) {
    foreach ($posts as $post) {
        $post->post_title .= ' - Modified';
    }
    return $posts;
}
add_filter('posts_results', 'modify_post_titles', 10, 2);

This example appends ” – Modified” to each post’s title in the $posts array.

Set All Posts to Draft Status

function set_posts_to_draft($posts, $query) {
    foreach ($posts as $post) {
        $post->post_status = 'draft';
    }
    return $posts;
}
add_filter('posts_results', 'set_posts_to_draft', 10, 2);

This example sets the status of all posts in the $posts array to ‘draft’.

Exclude Posts with Specific IDs

function exclude_specific_posts($posts, $query) {
    $excluded_ids = array(12, 34, 56);
    $filtered_posts = array();

    foreach ($posts as $post) {
        if (!in_array($post->ID, $excluded_ids)) {
            $filtered_posts[] = $post;
        }
    }
    return $filtered_posts;
}
add_filter('posts_results', 'exclude_specific_posts', 10, 2);

This example removes any posts with the IDs 12, 34, and 56 from the $posts array.

Add Custom Property to Post Objects

function add_custom_property($posts, $query) {
    foreach ($posts as $post) {
        $post->custom_property = 'Custom Value';
    }
    return $posts;
}
add_filter('posts_results', 'add_custom_property', 10, 2);

This example adds a custom property called ‘custom_property’ with the value ‘Custom Value’ to each post object in the $posts array.

Limit Post Results

function limit_post_results($posts, $query) {
    return array_slice($posts, 0, 3);
}
add_filter('posts_results', 'limit_post_results', 10, 2);

This example limits the number of posts in the $posts array to 3 by using array_slice().