Limiting returned wordpress fields from WP_Query or 'get' functions Limiting returned wordpress fields from WP_Query or 'get' functions wordpress wordpress

Limiting returned wordpress fields from WP_Query or 'get' functions


I used fields parameter in the query and run get posts on this query. For example: In my case, I just needed to get the Post ids for multiple categories, so I created a query like this:

$the_query = new WP_Query( array(                         'ignore_sticky_posts' => 1,                        'posts_per_page'      => -1,                        'cat'                 => '2,6,7' ,                        'fields'              => 'ids',                        'post_type'           => 'post',                        'post_status'         => 'publish',                                 )                         );

Run the get_posts on this query:

$posts = $the_query->get_posts();

$posts will get only the IDs of particular categories posts.

Or it can also be done with the standard and popular way and i.e., by running the loop of have_posts:

if ( $the_query->have_posts() ) {        while ( $the_query->have_posts() ) {            $the_query->the_post();            $post_id_array[] = get_the_ID();         }               }

These are the two ways to help with speeding up the response from the server and reducing the amount of data retrieved


WP_Query will return objects...so it's pretty fast. However, if you really want to limit what's returned, you can do so with the Return Fields Parameter of WP_Query.


This is what I've done to limit the fields from WP_Query, especially, when I want to json_encode them. The $return variable contains my array of posts with only the fields listed in the $fields array.

    $query = new WP_Query( array( 'post_type' => 'my_custom_type' ) );    $return = array();      $fields = array('post_title', 'ID');  //list of fields I want in $return    $posts = $query->get_posts();    foreach($posts as $post) {        $newPost = array();        foreach($fields as $field) {            $newPost[$field] = $post->$field;        }        $return[] = $newPost;    }