Looking to limit the returned fields of a WP Query to help with speeding up the response from the server and reducing the amount of data retrieved. For the query I’m using, it only needs up to 3 fields of data, the rest is brought in through ACF get_field_object in the loop. Other functions I’m using such as get_posts or get_terms have field options but are limited to a small number of things, such as ‘slug’ only or ‘id => slug’.
I’m used to developing in CakePHP, which has the option to specify each and every field to return, but the project calls for wordpress for other functionality and so I’m quite limited.
TL;DR need to speed up getting posts from WordPress
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:
Run the get_posts on this query:
$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:
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 ofWP_Query
.I don’t know how much it will help but below is how I’m getting a flattened array from a CPT. It’s not the fastest but it could be worse. I’m using ACF to get a Custom Field but you could just get back the slug or you could get back multiple fields instead:
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.Interestingly enough, you can do this with the WP Rest API using the _fields parameter
More info on the API here: https://developer.wordpress.org/rest-api/