I have a multisite network of sites which should display blog content from each other if the blog post has a tag with the site name.
To gather all posts within the network I use the SWT (Sitewide Tags) plugin as it seems most efficient. I store all posts in the main site (blog id 1) and from my other sites I want to query the main sites posts table for posts containing a tag with the querying site’s domain name.
I have working code in a page template (home.php
) – see below – but I understand the action pre_get_posts
are the way to go, but I can’t seem to figure out how to change the table to query. Should I perhaps do a JOIN in the action posts_join
?
If my solution seems to be way more complicated than it should be, feel free to bash me with other suggestions 🙂
This is my current template code:
$tags = array(
'lundalogik-se'
);
switch_to_blog(1);
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$wp_query = new WP_Query(array(
'post_status' => 'publish',
'paged' => $paged,
'orderby' => 'date',
'order' => 'desc',
'tag' => implode(",", $tags)
));
while (have_posts()) : the_post();
[..]
How can I rewrite this in pre_get_posts
?
Note; as you see the tag I’m searching for is static at the moment, this will change to match the domain name + ccTLD of the querying site or something similar later on.
Note 2; I’d rather not use switch_to_blog()
since I read it’s expensive but haven’t found a best practice for querying other blogs inside a network. Should I set the table name to query manually instead?
I have read most posts both here, in blogs and in the Codex (WP_Query, pre_get_posts etc.) touching multisite querying but almost all talks of using switch_to_blog and restore_current_blog.
OK so for reference I ended up actually using
switch_to_blog()
andrestore_current_blog()
. I found no references whatever for querying multiple tables (except writing my ownJOIN
-statements) when followed the source code for the actionpre_get_posts
.A lot of advice was given to skip
restore_current_blog()
to save CPU-cycles but when I checked the source code for this I saw that it would cause a huge memory problem since the main thingrestore_current_blog()
does is to pop the latest inserted object in a global array and this array would grow hugely with eachswitch_to_blog()
that one does not do arestore_current_blog()
on.Please feel free to check the source code and also see @user42826’s answer regarding this at https://wordpress.stackexchange.com/a/123516/14820.
For those who are interested, I ended up with transients both for the site-list and for the result to save both CPU-cycles and DB performance. I only needed data to be updated if it were stale (15 minutes or more of age). Only relevant bit of function included below:
Try the following:
You may need to change wp_posts to your main blog’s post table name.