0

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.?

1 Answer 1

1

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.

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.