Multisite is a powerful feature that allows us to manage multiple blogs within a single WordPress installation. In this post I briefly describe how to post content from the main site to a sub-site.
// Check if WordPress is using multisite
if ( is_multisite() ) {
global $switched;
// Switch to another blog by ID number 1 for the first site
switch_to_blog( 1 );
// Get a WP_Query that loops in a post from the main site
get_template_part('template-parts/notice-wp-query');
// Switch back to current blog
restore_current_blog();
}
We can use any method you like to query a post from the main site. In this example I’m using WP_Query and Advanced Custom Fields to display a post using the notice category.
<?php
$current_post_ID = get_the_ID(); // the post's id is assigned to $current_post_ID
$args = array(
'post_type' => 'post',
'orderby' => 'date',
'order' => 'DESC',
'category_name' => 'notice',
);
// the query
$the_query = new WP_Query( $args );
?>
<?php if ( $the_query->have_posts() ) : ?>
<!-- pagination here -->
<div id="notice" class="row">
<div class="small-12 columns">
<!-- the loop -->
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<article>
<div class="notice">
<?php
if ( function_exists( 'get_field' ) ) {
echo '<a href="' . get_field( 'redirect_to_url' ) . '">';
echo '<h1 class="entry-title"><span class="dashicons dashicons-warning"></span>' . get_the_title() .'</h1>';
echo '<div class="notice-content">';
echo the_content();
echo '</div>';
echo '</a>';
} else {
echo '<a href="' . get_permalink() . '">';
echo '<h1 class="entry-title"><span class="dashicons dashicons-warning"></span>' . get_the_title() .'</h1>';
echo '<div class="notice-content">';
echo the_content();
echo '</div>';
echo '</a>';
}
?>
</div>
</article>
<?php endwhile; ?>
<!-- end of the loop -->
</div>
</div>
<!-- pagination here -->
<?php endif; ?>
<?php wp_reset_postdata();
Allowing the site to post a custom message that links to another page for additional information. When the post isn’t available the blue box below will simply not appear on the page. I built this feature a long time ago but didn’t really have a practical use of until March when the pandemic required notification banners above everything on my 100+ site multisite.