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

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

Leave a Reply

Your email address will not be published. Required fields are marked *