Skip to content

Instantly share code, notes, and snippets.

@danielhomer
Last active May 23, 2019 10:42
Show Gist options
  • Save danielhomer/ed632633a6d5308d017258bd0d591d7d to your computer and use it in GitHub Desktop.
Save danielhomer/ed632633a6d5308d017258bd0d591d7d to your computer and use it in GitHub Desktop.
WordPress - Check network site for post before 404'ing
<?php
/**
* This filter will attempt to fetch a post from the main site if a post cannot be found
* on a child site.
**/
add_filter( 'the_posts', function( $posts, $wp_query ) {
$network_id = get_network()->site_id;
if ( ( ( count( $posts ) === 0 && is_single() ) || is_archive() || is_home() ) && get_current_blog_id() !== $network_id ) {
switch_to_blog( $network_id );
$network_query = new WP_Query();
$network_query->query( $wp_query->query_vars );
$posts = $network_query->posts;
restore_current_blog();
foreach ( $posts as $key => $post ) {
$localised = get_posts( [
'name' => $post->post_name,
'posts_per_page' => 1,
] );
if ( count( $localised === 1 ) && is_a( $localised[0], 'WP_Post' ) ) {
$posts[ $key ] = $localised[0];
}
}
}
return $posts;
}, 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment