Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm running a custom WP_Query and find the following SQL running as part of it.

SELECT t.*, tt.*, tr.object_id FROM wp_terms AS t INNER JOIN wp_term_taxonomy AS tt ON tt.term_id = t.term_id INNER JOIN wp_term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ('category', 'post_tag') AND tr.object_id IN (381, 383, 389, 395) ORDER BY t.name ASC

Now within the loop I'm using wp_get_object_terms( $post->ID, 'post_tag' ); to retrieve post tags. This results in additional SQL queries for each post to retrieve post tags. Something I believe shouldn't be necessary when the post tags were fetched when the WP_Query initial ran.

WordPress is smart enough not to do this with post meta, as any number of calls to get_post_meta within the loop never results in additional SQL queries.

How can I retrieve the post tags and possibly the categories from the original WP_Query and avoid extra SQL queries.?

share|improve this question

1 Answer 1

up vote 0 down vote accepted

Resolved this by using get_the_tags($post->id); instead of wp_get_object_terms( $post->ID, 'post_tag' );.

get_the_tags($post->id); hooks onto the WP_Query within the loop and retrieves the tags without the need of additional SQL queries.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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