How to return only certain fields using get_posts()

I’m trying to get only the fields that I need using the get_posts() function in WordPress. I currently have the following code:

    $posts_args = array(
        'orderby' => 'post_date',
        'order' => 'DESC',
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => 5,
        'fields' => 'ids'
    );

    $post_ids_r = get_posts($posts_args);

This works fine if I only want to get the id. But if I want to get the permalink or the title of the post along with the ids that’s where I’m not sure what to do. I already tried the following:

'fields' => array('ids', 'post_titles')
'fields' => 'ids,post_titles'
'fields' => 'ids,titles'
'fields' => array('ids','titles')

But nothing works, I guess the only one that it recognizes is the ids field. Is there any other way to do this if its really not possible to do it using get_posts()? Thanks in advance.

6 s
6

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