Fix wp_term_relationships slow query in get_posts

I used the Query Monitor plugin to find slow query on my WordPress site. The below-mentioned WP_Query-get_posts() takes about 0.3446 query time out of the total Database Query time of 0.3976.

SELECT wp_posts.ID
FROM wp_posts 
LEFT JOIN wp_term_relationships
ON (wp_posts.ID = wp_term_relationships.object_id)
WHERE 1=1 
AND wp_posts.ID NOT IN (203598)
AND ( wp_term_relationships.term_taxonomy_id IN (17) 
OR wp_term_relationships.term_taxonomy_id IN (11652,20693,21952,23971,24907,24908,25928) )
AND wp_posts.post_type = 'post'
AND ((wp_posts.post_status = 'publish'))
GROUP BY wp_posts.ID
ORDER BY wp_posts.post_date DESC
LIMIT 0, 6

I'm guessing it has something to do with the 20,000+ Tags used on posts on my site. Is that so? If yes, how do you suggest fixing this slow query? Or how should I go about deleting Tags which aren't used in more than 5 posts of all the posts on the site?

Please help.

Topic mysql wp-query tags database Wordpress

Category Web


I have encountered the same issue but with product attributes, since I had more than 20000 products and much more product attributes, the queries were very slow.

What I did was, in order to make it faster, wrote an small plugin converting tags to custom fields and then displayed those on the page, but in your case if you need the tag archive pages and its functionalities, I suppose there is no other way around it.

To avoid max_execution_time try to configure your plugin to execute tag conversion instructions in small chunks,For instance, From posts 1 to 2000 and 2000 to 4000 and so on.

Database indexing might help too.

Finally try to use a cache plugin such as wp_fastest_cache it helps in an immense degree.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.