I’m building (mostly with a self-teaching purpose) a simple plugin to query posts from another blog on a MS network via a shortcode (like [network-posts blogs=”8" layout=”grid” columns=”3"]), but I’m running into some performance issues/doubts.
Here's the issue:
To my understanding (and maybe I’m wrong), when creating and looping through a
new WP_Query, only 1 new query should be executed on the database.
When I use the shortcode (without switching to another blog), 7 new database queries are added.
When I switch to another blog (just 1 switch), the additional queries become 32.
The additional queries are called by
and comes in the form of an handful of selects:
SELECT post_id, meta_key, meta_value FROM wp_11_postmeta WHERE post_id IN (109) ORDER BY meta_id ASC
SELECT * FROM wp_11_posts WHERE ID = 109 LIMIT 1
When switching to another blog, this two queries are duplicated for each post that's being loaded.
Is there a way to reduce the number of database queries?
The plugin is on github and this is the link to a simplified branch that I’m using for debugging purposes:
switch_to_blog() is commented in the php code, but you can activate it by uncommenting line 40 and 64.
EDIT: the plugin has just ~70 lines of code distributed over two files. I didn't paste the code here because I thought it would have been more readable on github.