Recent Posts From Across the Network
Adds a [wpide_network_posts] shortcode that shows the newest posts from every public site on the network in one list, with the site name next to each post.
Opens WPIDE on
Code
if ( ! is_multisite() ) {
return;
}
add_shortcode( 'wpide_network_posts', function ( $atts ) {
$atts = shortcode_atts( array( 'number' => 10, 'sites' => '' ), $atts, 'wpide_network_posts' );
$limit = min( 30, max( 1, absint( $atts['number'] ) ) );
$ids = array_filter( array_map( 'absint', explode( ',', $atts['sites'] ) ) );
$key = 'wpide_network_posts_' . md5( $limit . '|' . implode( ',', $ids ) );
$items = get_site_transient( $key );
if ( false === $items ) {
$items = array();
$sites = get_sites( array(
'site__in' => $ids,
'public' => 1,
'archived' => 0,
'spam' => 0,
'deleted' => 0,
'number' => 50,
'orderby' => 'last_updated',
'order' => 'DESC',
'fields' => 'ids',
) );
foreach ( $sites as $blog_id ) {
switch_to_blog( $blog_id );
$name = get_bloginfo( 'name' );
foreach ( get_posts( array( 'numberposts' => $limit, 'no_found_rows' => true ) ) as $post ) {
$items[] = array(
'time' => strtotime( $post->post_date_gmt ),
'title' => get_the_title( $post ),
'url' => get_permalink( $post ),
'site' => $name,
);
}
restore_current_blog();
}
usort( $items, function ( $a, $b ) {
return $b['time'] <=> $a['time'];
} );
$items = array_slice( $items, 0, $limit );
set_site_transient( $key, $items, 30 * MINUTE_IN_SECONDS );
}
if ( ! $items ) {
return '';
}
$html = '<ul class="wpide-network-posts">';
foreach ( $items as $item ) {
$html .= sprintf(
'<li><a href="%1$s">%2$s</a> <small>%3$s · %4$s</small></li>',
esc_url( $item['url'] ),
esc_html( $item['title'] ),
esc_html( $item['site'] ),
esc_html( wp_date( get_option( 'date_format' ), $item['time'] ) )
);
}
return $html . '</ul>';
} );
Notes
Looks at up to 50 of the most recently updated public sites and caches the result for 30 minutes; attributes are number and sites (comma-separated blog IDs to limit the list).
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.