2

I have a sidebar widget that will display related posts based on a custom meta field. The query works, but its very wasteful. All i need is the post title, featured image and the categories of the post. Currently the following query is returning all of the content for the post along with a massive amount of data that i dont need. I dont want to be killing my server by pulling huge amounts of data from the database that i dont need

$myquery = new WP_Query( "post_type=post&meta_key=nb_gameids_key&meta_value=14&order=ASC" );

To best explain the data i want ill use an sql query that would give me the data i want. I know the database isnt structured this way its just for an example.

SELECT title,image,category FROM posts WHERE nb_gameids_key = 14 ORDER BY datecreated LIMIT 6

1 Answer 1

3

You don't need to worry to much about your query as there is not much you can do about it. You can unfortunately not just only query categies, post titles and images natively using WP_Query. Post categories needs to be called separately inside the loop, just like featured images.

If you dig deeper into core, you will see that all postdata and post terms are cached, so when you think you are making extra db calls, you are not. The cache is first checked for the requires data, if it is, the data is retrieved from the cache, otherwise the db is queried and the data is cached for later queries.

You can add 'no_found_rows' => true, to your arguments if you are not going to paginate your query. This makes the query faster as it ignores pagination. Alternatively, you can use get_posts which has this already build in

Also, you can make use of transients to store the result from a query and only flush the transient when a new post is added in a particular category or custom field

3
  • ah, well this is good to know i guess. Even when its reading from cache its always nice to only load the data that is needed and not excess. I guess if i have no other option i can just pick what i need from the wp_query object Commented Jul 25, 2015 at 16:22
  • I learned something from here @PieterGoosen
    – prosti
    Commented May 20, 2016 at 20:24
  • @prosti glad to hear you found my answer useful Commented May 21, 2016 at 8:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.