The posts_fields filter allows you to modify the SELECT clause of the query when retrieving posts from the WordPress database.
Usage
add_filter('posts_fields', '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
Examples
Add Post Thumbnail URL to the Query
Add the post thumbnail URL to the post fields by using a JOIN and SELECT statement.
add_filter('posts_fields', 'add_post_thumbnail_url', 10, 2); function add_post_thumbnail_url($fields, $query) { global $wpdb; $fields .= ", CONCAT('$wpdb->postmeta.meta_value') as post_thumbnail_url"; return $fields; }
Add Custom Meta Field to the Query
Add a custom meta field ‘price’ to the post fields.
add_filter('posts_fields', 'add_price_to_fields', 10, 2); function add_price_to_fields($fields, $query) { global $wpdb; $fields .= ", $wpdb->postmeta.meta_value as price"; return $fields; }
Select Only Post Titles and IDs
Modify the query to select only post titles and IDs.
add_filter('posts_fields', 'select_post_titles_and_ids', 10, 2); function select_post_titles_and_ids($fields, $query) { global $wpdb; $fields = "$wpdb->posts.ID, $wpdb->posts.post_title"; return $fields; }
Add Comment Count to the Query
Include the comment count of each post in the query.
add_filter('posts_fields', 'add_comment_count', 10, 2); function add_comment_count($fields, $query) { global $wpdb; $fields .= ", COUNT($wpdb->comments.comment_ID) as comment_count"; return $fields; }
Select Only Published Posts with a Specific Tag
Modify the query to select only published posts with a specific tag.
add_filter('posts_fields', 'select_published_posts_with_tag', 10, 2); function select_published_posts_with_tag($fields, $query) { global $wpdb; $fields .= " AND $wpdb->term_relationships.term_taxonomy_id = 10"; return $fields; }