Querying posts from multiple sites in a network?

I know you said you’d rather not install a plug-in, but that’s exactly what you want to do in this situation. Placing the code in your theme’s functions.php file requires you to either use the same theme across all sites in the sub-network or maintain multiple copies of the same file. On the other hand, you can create a simple plug-in for the network to encapsulate the functionality, then activate it on the network, and immediately have the functionality available with only one file to maintain. This would actually create less bloat than depending on your functions.php files.

The thing to keep in mind here is that you’re either going to need to loop through each site on the network to find your posts or perform a custom query. I’d opt for the second routine because, though it’s a bit more complicated, it’s a single query rather than a different query for each blog.

Basically … you’ll need to do the following:

  1. Get a list of all the blog IDs in the network/sub-network. If using a vanilla installation, this can be found in the wp_blogs table. Just do a simple SELECT query to load up an array, then you can loop through to add each blog to your main query.
  2. Create a loop that adds each blog to a large query. You’ll need to be JOINing tables together and searching based on blog_id (from wp_blogs), post_id (from wp_BLOG_posts), and the custom taxonomy.

Like I said, it’s not a simple solution (the SQL statement will be very complicated and I don’t have time to hack through it at the moment), but it will be a single statement that does all the work.

Alternatively …

  1. Get a list of the blog IDs and store it in an array.
  2. Iterate through your array querying each blog in the network and appending your matches (posts with a certain taxonomy term) to a separate array.

With the alternative method you’ll have to run a separate query for every blog in the network. If your network is 10-20 sites this isn’t too much of an issue. If your network is 200-500 sites expect some performance issues to start cropping up.

Also, you should cache the results of your query if at all possible. If it’s being run on multiple page loads (i.e. for a sidebar widget shared across the network) then you only want to run the query when there’s new data to get. Otherwise, serve up the cached results so you don’t slow down the network.

Leave a Comment