Using WordPress ‘posts_fields_request’ PHP filter

The ‘posts_fields_request‘ WordPress PHP filter allows you to modify the SELECT statement used to retrieve posts from the database.

This filter is useful if you need to add custom fields to the SELECT statement or modify the default fields.

Usage

add_filter('posts_fields_request', 'your_custom_function', 10, 2);
function your_custom_function($fields, $query) {
    // your custom code here
    return $fields;
}

Parameters

  • $fields (string): The SELECT clause of the query.
  • $query (WP_Query): The WP_Query instance (passed by reference).

More information

See WordPress Developer Resources: posts_fields_request

Examples

Select Post ID and Title Only

Select only the post ID and title from the query.

add_filter('posts_fields_request', 'select_post_id_and_title', 10, 2);
function select_post_id_and_title($fields, $query) {
    $fields = "ID, post_title";
    return $fields;
}

Add Custom Field to Query

Add a custom field called “price” to the query.

add_filter('posts_fields_request', 'add_custom_field_price', 10, 2);
function add_custom_field_price($fields, $query) {
    $fields .= ", meta_value AS price";
    return $fields;
}

Add Post Author Name to Query

Add the post author name to the query.

add_filter('posts_fields_request', 'add_post_author_name', 10, 2);
function add_post_author_name($fields, $query) {
    $fields .= ", users.display_name AS author_name";
    return $fields;
}

Modify Select Clause for Custom Post Type

Modify the SELECT clause only for a custom post type called “book”.

add_filter('posts_fields_request', 'modify_select_for_book_post_type', 10, 2);
function modify_select_for_book_post_type($fields, $query) {
    if ('book' == $query->get('post_type')) {
        $fields = "ID, post_title, post_date";
    }
    return $fields;
}

Add Post Thumbnail URL to Query

Add the post thumbnail URL to the query.

add_filter('posts_fields_request', 'add_post_thumbnail_url', 10, 2);
function add_post_thumbnail_url($fields, $query) {
    $fields .= ", (SELECT guid FROM wp_posts WHERE ID = (SELECT meta_value FROM wp_postmeta WHERE post_id = wp_posts.ID AND meta_key = '_thumbnail_id')) as thumbnail_url";
    return $fields;
}