Querying Posts by Taxonomy From Alternate Network Site

After some thought, I came up with a possible “solution”. However, it wasn’t exactly the route I hoped to take.

The custom post type and all custom taxonomies for that custom post type must be registered on ALL network sites in order for WP_Query(); to fetch posts from the primary site from any of the sub sites in the network.

At least as a temporary solution, I have specified the following settings to help “hide” the custom post types and custom taxonomies from the sub sites.

Firstly, I specified two global variables to use through out my plugin. One for the primary site ID, and another for the current site ID. These variables can then be globalized into any class methods or functions.

$GLOBALS['mbe_primary_site_id'] = 1;
$GLOBALS['mbe_current_site_id'] = get_current_blog_id();

While registering the custom post type… I added a check, and altered some of the post type registration arguments.

global $mbe_primary_site_id, $mbe_current_site_id;
if($mbe_current_site_id != $mbe_primary_site_id){
    $args['show_ui'] = false;
    $args['public'] = false;
    $args['show_in_menu'] = false;
}

While registering the custom taxonomies… I added a check, and altered some of the taxonomy registration arguments.

global $mbe_primary_site_id, $mbe_current_site_id;
if($mbe_current_site_id != $mbe_primary_site_id){
    $args['show_ui'] = false;
    $args['public'] = false;
}

So now, I can query posts by taxonomy from the primary site on any of the sub sites like: switch_to_blog($mbe_primary_site_id);, WP_Query(...);, and restore_current_blog();

I don’t know if there’s a real solid way around this. What I do know is this method works, and if you were to do it via $wpdb; queries, there would be quite some conditional logic and checks involved, especially if you plan on paginating the content.

It would just be more of a pain and a lot of extra work to use $wpdb; for everything, when you could just register the custom post types and custom taxonomies on the sub sites as well, and just hide access to them on the sub sites.

Leave a Comment