Latest Posts From the Main Site on Any Subsite
Adds a [wpide_main_site_posts] shortcode that lists the newest posts from the network's main site, perfect for a "News from HQ" box on every subsite.
Opens WPIDE on
Code
if ( ! is_multisite() ) {
return;
}
add_shortcode( 'wpide_main_site_posts', function ( $atts ) {
$atts = shortcode_atts( array( 'number' => 5, 'category' => '' ), $atts, 'wpide_main_site_posts' );
$key = 'wpide_main_posts_' . md5( absint( $atts['number'] ) . '|' . sanitize_title( $atts['category'] ) ) . '_' . (int) get_site_option( 'wpide_main_posts_ver', 1 );
$html = get_site_transient( $key );
if ( false === $html ) {
switch_to_blog( get_main_site_id() );
$posts = get_posts( array(
'numberposts' => min( 20, max( 1, absint( $atts['number'] ) ) ),
'category_name' => sanitize_title( $atts['category'] ),
'no_found_rows' => true,
'suppress_filters' => false,
) );
$html = '';
if ( $posts ) {
$html = '<ul class="wpide-main-site-posts">';
foreach ( $posts as $post ) {
$html .= sprintf(
'<li><a href="%1$s">%2$s</a> <time datetime="%3$s">%4$s</time></li>',
esc_url( get_permalink( $post ) ),
esc_html( get_the_title( $post ) ),
esc_attr( get_the_date( 'c', $post ) ),
esc_html( get_the_date( '', $post ) )
);
}
$html .= '</ul>';
}
restore_current_blog();
set_site_transient( $key, $html, 15 * MINUTE_IN_SECONDS );
}
return $html;
} );
add_action( 'transition_post_status', function ( $new, $old, $post ) {
if ( is_main_site() && 'post' === $post->post_type && ( 'publish' === $new || 'publish' === $old ) ) {
update_site_option( 'wpide_main_posts_ver', (int) get_site_option( 'wpide_main_posts_ver', 1 ) + 1 );
}
}, 10, 3 );
Notes
Attributes: number (default 5) and category (a category slug on the main site). Cached for 15 minutes and refreshed when the main site publishes.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.