HOMEBlogWordPressWordPress Multisite Recent Posts: 3 Easy Steps to…

WordPress Multisite Recent Posts: 3 Easy Steps to Display Network Posts on Your Main Site

WordPress Multisite Recent Posts

A standard WP_Query on a WordPress multisite main site only searches that site, so it misses posts published on subsites. To build WordPress Multisite Recent Posts, add a small custom shortcode that gathers published posts from eligible public network sites and displays the newest results on the main site.

This guide uses WordPress multisite APIs in a PHP plugin file, then adds the shortcode to a page or template. The implementation limits how many sites and posts it checks and filters out sites that should not appear. If your network is larger than the chosen site limit, use an explicit site allowlist or pagination, and consider caching the results to reduce repeated queries.

Prerequisites

Prepare the network and deployment path before adding the aggregator. Confirm who can install the code, which sites should contribute posts, and how you will test the change safely.

  • A working WordPress Multisite network, PHP 8.0 or newer, and access to the main site and Network Admin.
  • Permission to create a small custom plugin or must-use plugin, plus file access through your hosting control panel, SFTP, or SSH.
  • A staging environment for testing and a recent, restorable backup of the database and site files before deploying PHP changes.
  • A clear eligibility decision: identify which public network sites may appear and whether the main site should contribute its own posts.
  • Basic familiarity with adding a shortcode to a WordPress page or template, and a plan for where the combined list should appear.

Confirm the network scope and visibility rules

A standard WP_Query runs in the current site context; on the main site, it does not automatically search posts stored by subsites. Before building the aggregator, decide whether the main site should contribute posts alongside subsites. Include it only if that matches the intended list, so its posts are not unexpectedly missing or duplicated by a separate display.

Define the eligible sites as public, not archived, not marked as spam, and not deleted. The resulting list should contain published posts only; site eligibility does not make drafts or private posts appropriate for a public-facing feed. Start with a documented limit of 100 sites. That cap bounds work, but it does not guarantee coverage when the network has more than 100 eligible sites. For larger networks, use an explicit allowlist or paginate site retrieval rather than implying that the first batch represents the whole network.

Inspect sites and choose a safe result limit

When you retrieve site IDs, apply the visibility and status filters through get_sites(), then set a deliberate site limit. The official get_sites() reference describes its query arguments. Separately, cap the shortcode post count with absint() and minimum/maximum values so a page editor cannot request an unbounded amount of work.

Inspect sites and choose a safe result limit

Use get_sites() to define the network boundary before querying posts. Set public to 1, and archived, spam, and deleted to 0 so the collection excludes sites that should not contribute to a public list. Request site IDs rather than full site objects when possible, and set number to a documented cap such as 100. See the official get_sites() reference for the supported arguments.

A site cap is a performance boundary, not proof that every network site was checked. If more than 100 eligible sites exist, use an explicit allowlist or retrieve sites in pages; do not silently present a capped scan as complete coverage. Separately, validate the shortcode post count before using it in a query. Convert the input with absint(), then clamp it, for example, to a minimum of 1 and a maximum of 50. This prevents negative, zero, or excessively large values from triggering unintended query work while keeping the requested result size predictable.

Build a network-aware recent-post shortcode

There is no ordinary cross-network WP_Query: it searches the active site only. This shortcode retrieves eligible site IDs, switches into each site, queries its published posts, and captures the title, permalink, site name, local date, and sortable timestamp before restoring the original context.

Install this complete implementation in a custom plugin or must-use plugin. Each local query is bounded by the validated count; the merged results are then sorted newest-first and trimmed to that count.

PHP
<?php
function pnet_network_recent_posts_shortcode( $atts ) {
    $atts = shortcode_atts( array( 'count' => 10 ), $atts, 'pnet_network_recent_posts' );
    $count = max( 1, min( 50, absint( $atts['count'] ) ) );
    $site_ids = get_sites( array(
        'public' => 1, 'archived' => 0, 'spam' => 0, 'deleted' => 0,
        'number' => 100, 'fields' => 'ids',
    ) );
    $items = array();

    foreach ( (array) $site_ids as $site_id ) {
        if ( ! switch_to_blog( (int) $site_id ) ) {
            continue;
        }
        try {
            $site_name = get_bloginfo( 'name' );
            $query = new WP_Query( array(
                'post_type' => 'post', 'post_status' => 'publish',
                'posts_per_page' => $count, 'orderby' => 'date', 'order' => 'DESC',
                'no_found_rows' => true, 'ignore_sticky_posts' => true,
            ) );
            foreach ( $query->posts as $post ) {
                $items[] = array(
                    'title' => get_the_title( $post ),
                    'url' => get_permalink( $post ),
                    'site' => $site_name,
                    'date' => get_the_date( get_option( 'date_format' ), $post ),
                    'timestamp' => (int) get_post_timestamp( $post ),
                );
            }
        } finally {
            restore_current_blog();
        }
    }

    usort( $items, function ( $a, $b ) {
        return $b['timestamp'] <=> $a['timestamp'];
    } );
    $items = array_slice( $items, 0, $count );
    if ( empty( $items ) ) {
        return '<p class="pnet-network-recent-posts-empty">No recent posts are available.</p>';
    }

    $html = '<ul class="pnet-network-recent-posts">';
    foreach ( $items as $item ) {
        $html .= '<li><a href="' . esc_url( $item&#91;'url'&#93; ) . '">' . esc_html( $item['title'] ) . '</a>';
        $html .= '<span>' . esc_html( $item['date'] ) . ' · ' . esc_html( $item['site'] ) . '</span></li>';
    }
    return $html . '</ul>';
}

function pnet_register_network_recent_posts_shortcode() {
    add_shortcode( 'pnet_network_recent_posts', 'pnet_network_recent_posts_shortcode' );
}
add_action( 'init', 'pnet_register_network_recent_posts_shortcode' );

Site-dependent values are collected while the correct site is active, and finally restores context even if collection fails. The filters include public sites and exclude archived, spam, or deleted sites; the main site is included when it meets those rules. See the official switch_to_blog() reference for context-switch behavior.

WordPress Multisite Recent Posts - Network Feed Flow
Network Feed Flow
Pro Tip
A fixed 100-site scan is a deliberate safety limit, not full coverage for larger networks. Use an allowlist or paginated retrieval when your network exceeds that cap.

Register the shortcode and validate its attributes

The implementation above registers pnet_network_recent_posts with add_shortcode() during the init action. WordPress passes any shortcode attributes to the callback, where shortcode_atts() supplies a safe default of 10 when the count is omitted. Keeping registration separate from the callback makes the shortcode available after WordPress has initialized its hooks.

The callback converts the requested count with absint(), then clamps it to the range of 1–50. This handles negative or invalid input and prevents an editor from requesting an excessive number of results. The code deliberately accepts no site IDs or post types: sites are selected by the network visibility rules, and the query is restricted to published posts. This keeps the shortcode interface small and avoids exposing controls that would need additional validation.

To display ten results, add this exact shortcode to a Shortcode block on the main site:

[pnet_network_recent_posts count="10"]

Change the number as needed within the allowed range. If the attribute is absent or resolves to zero, the callback still uses the minimum of one result rather than running an unbounded query.

Switch sites, collect posts, and restore context

Each site query must run while that site is active. Loop over the eligible IDs, call switch_to_blog(), then collect the site name and each post’s title, permalink, display date, and sortable timestamp before leaving that context. Site-dependent functions can return different values after you switch back, so capture everything needed for rendering while the source site is active.

Always pair the context change with restore_current_blog() in a finally block. One important correction to the earlier loop: do not skip a site just because switch_to_blog() returns false. WordPress can return false when the requested site is already active; that call still needs its matching restore to keep the switch stack balanced. Since these IDs come from get_sites(), call the switch directly, then enter the protected collection block. The official switch_to_blog() reference describes this API.

Do not echo markup during collection. Append plain values to the results array, restore the original site context, then sort and render the complete list once. Escape titles and site names with esc_html() and links with esc_url() at output time. This keeps later main-site queries in the expected context and prevents untrusted content from being inserted as HTML.

Sort and render a safe combined list

Each site contributes a small array of captured post details. Once the loop finishes and the original site context is restored, the shortcode sorts those combined results by their numeric timestamps in descending order, so the newest post appears first regardless of which site published it. It then slices the sorted array to the validated count. Because each local query collects at most that many posts, the merge remains bounded by the configured site limit and count.

Render the final results as a semantic unordered list. Each item should link the post title and show its date and source-site name, helping visitors identify where the article originated. The implementation escapes titles and site labels with esc_html() and links with esc_url(); keep escaping at output time even when values were collected earlier.

The date is formatted while its source site is active, using that site’s date format and timezone settings, then retained as display text. If no eligible published posts were found, return a brief empty-state message instead of an empty list. This keeps the shortcode output useful and avoids confusing blank space on the main-site page.

Install the code without editing WordPress core

Save the shortcode implementation in a small custom plugin or a must-use plugin instead of changing WordPress core. For a must-use plugin, create wp-content/mu-plugins/ if it does not already exist, then create wp-content/mu-plugins/pnet-network-recent-posts.php. Put the PHP opening tag and the complete implementation from the previous step in that file. WordPress loads must-use plugins automatically, so there is no activation step.

Alternatively, place the code in a standard custom plugin and network-activate it if the shortcode needs to be available across the network. The display can still be placed on a page on the main site. Keep the plugin in version control or retain a copy of the deployed file so updates and rollback are straightforward; do not make edits to core files or rely solely on the active theme file.

Backup Required
Back up the database and site files before deployment, and test the plugin on staging first. Never paste PHP code into a page editor; install it as a plugin file and check the page for errors before deploying to production.

After saving the file, visit the staging main site and confirm the shortcode is available. If a PHP error occurs, disable or remove the plugin file to restore the previous state, then correct and retest the code before deploying it live.

Add the shortcode to the main site

On a page on the network’s main site, add a Shortcode block and enter [pnet_network_recent_posts count="10"]. The shortcode gathers the latest eligible posts when WordPress renders that page, so you do not need to copy post titles or update the list manually. Adjust the count to any value from 1 to 50.

For a PHP template used by a page on the main site, call the shortcode with do_shortcode(). The guarded helper below uses a pnet_-prefixed function and can be placed in the relevant template. Do not add this PHP to a page editor.

Use the block-editor method when editors need to manage placement without touching theme files. Use the template method when the list belongs in a fixed location in your theme. In either case, confirm that the page is rendered on the main site and that the shortcode plugin is active.

WordPress Multisite Recent Posts - Main Site Shortcode
Main Site Shortcode

Verify the output and tune performance

On staging, publish dated test posts on at least two public subsites, then load the main-site page containing the shortcode. Confirm that posts from both sites appear together in newest-first order, with each title linking to its source site. Check that private, archived, spam, and deleted sites are excluded, and verify that the main site is included or omitted according to your chosen scope.

Also test an empty network, the minimum count of 1, and the maximum count of 50. After the shortcode runs, load another main-site page that uses site-specific queries; correct behavior helps confirm the original blog context was restored. If a result is missing or misordered, compare its published date and timezone with the value captured by the aggregator.

For a high-traffic page, cache the combined output or result data with a short, deliberate expiration, then invalidate that cache when an eligible post is published or updated. Test cache clearing after changing sample posts so stale results do not mislead visitors. Keep the 100-site limit as an explicit safety boundary: it is not full network coverage when more eligible sites exist. For larger networks, use an allowlist or paginated site retrieval and measure performance before increasing query work.

You might also like:

Master WordPress Data Sanitization for Secure Code : Stop Vulnerabilities

Worried about hackers? Learn how to lock down your plugins with proper WordPress Data Sanitization and validation. Secure your user...

Read more →

Common Errors

The list is empty: Check that eligible sites are public and not archived, spam, or deleted, and that they contain published posts. Review the get_sites() filters and confirm the main site inclusion rule matches your intended scope; private sites and drafts are deliberately excluded.

Posts are duplicated or stale: Clear the page cache and any persistent object cache after changing test posts or site settings. If you cache the aggregate, verify that publishing or updating an eligible post invalidates that cache.

Links or site labels are wrong: Capture each permalink and site name while that site is active. Collecting them after restore_current_blog() can return values from the main site instead of the source site.

Later queries behave unexpectedly: Audit every successful site switch and confirm restore_current_blog() runs in the finally path, including when collection encounters an error. An unbalanced switch can leave subsequent page code in the wrong site context.

The page is slow: Do not raise the site limit without measuring. Lower the cap, use an explicit site allowlist or paginate site retrieval, and add caching with a suitable invalidation plan for larger networks.

The shortcode appears as plain text: Confirm the plugin is active, the shortcode tag is exactly pnet_network_recent_posts, and the content is in a Shortcode block or another location that processes shortcodes.

You might also like:

Custom WordPress API Endpoint: Safely Register Routes in 4 Steps

Custom WordPress API Endpoint development doesn't have to be hard. Learn how to fetch specific data safely without bloating your...

Read more →

Conclusion

A standard main-site query cannot retrieve posts stored on other sites in a WordPress Multisite network. The custom shortcode solves that limitation by querying eligible sites individually, collecting their published posts, and merging them into one date-sorted list for the main site. It keeps the work bounded with a site cap and validated result count, filters out sites that should not contribute public content, and restores the original site context after every switch. Titles, site labels, and links are escaped when rendered, making the combined feed safer to display.

Test the implementation on staging and confirm that posts from the intended sites appear in the correct order with accurate source links. Add the shortcode to a main-site page after checking empty results, count limits, and exclusions. If the network exceeds the configured site cap, use an allowlist or paginated site retrieval rather than assuming every site was scanned. For a busy page, introduce caching with a clear expiration and invalidation plan for new or updated posts. These steps make WordPress Multisite Recent Posts a maintainable network-wide feature rather than a fragile one-off query.

Abhik

🚀 Full Stack WP Dev | ☕ Coffee Enthusiast | 🏍️ Biker | 📈 Trader
Hi, I’m Abhik. I’ve been coding since 2007, a journey that began when I outgrew Blogger and migrated to a robust self-hosted stack. That transition introduced me to WordPress, and I’ve been building professional solutions ever since.

Leave a comment