How to return only certain fields using get_posts()

get_posts passes the heavy lifting off to WP_Query and if you look at the source of that class you can see that there are only a limited number of options with that fields argument. There are only three options in that switchids, id=>parent, and the default case, everything.

You can use the posts_fields filter to alter what fields get returned, though it looks like you need to pass 'suppress_filters => false in the arguments in order to get that filter to run. It should look something like this:

function alter_fields_wpse_108288($fields) {
  return 'ID,post_title'; // etc
}
add_filter('posts_fields','alter_fields_wpse_10888');

However, there is a larger problem. The post objects that get returned are created by a call to get_post and it doesn’t honor the values passed into the original query and I don’t see a way to change what gets returned either in get_posts or in the WP_Post class itself.

Leave a Comment