How to Sync Announcements Across Multiple WordPress Websites Using WP REST API

Managing multiple WordPress websites under the same domain area can be challenging, especially when it comes to publishing global announcements.

One of my clients recently faced this exact problem. They operate five different businesses, each with its own WordPress website, but they wanted to publish announcements across all five sites simultaneously—without having to log in and update each site individually.

The Challenge: Centralized Announcements for Multiple WordPress Sites

The core issue was efficiency. The client needed a way to publish the same announcement across all five websites at the same time without manually updating each site. Managing this process manually was a tedious and time-consuming task, especially during peak business hours when announcements might change frequently—sometimes even multiple times a day.

The primary concerns were:

  • Each website had to display the same announcements at the same time.
  • Logging into each website separately and updating announcements manually was inefficient and resource-intensive.
  • A streamlined solution was required to publish and update announcements with minimal effort.

The Solution: Automating Announcement Syncing via WP REST API

Given that announcements mostly consist of text, links, and basic formatting (with minimal images or icons), I knew that leveraging the WordPress REST API was the perfect approach. The solution involved:

  1. Creating a Custom Post Type (CPT) Named “Announcements”
    • Since announcements needed to be published separately from standard WordPress posts and pages, a Custom Post Type (CPT) was required.
    • The CPT would allow structured content management and ensure that announcements remained organized across all websites.
  2. Developing a Custom WordPress Plugin to Sync Announcements
    • The plugin was installed on Main WordPress website, enabling them to sync announcements from a single, central website.
    • The parent website acted as the master source, while the other four websites fetched the latest announcements from it.
  3. Syncing Data Using WP REST API
    • POSTing announcements from the parent website to the child sites.
    • GETting the latest announcements on each child website dynamically.
    • Using application passwords for secure authentication while syncing data.

How It Works: Technical Implementation

The core functionalities of this solution revolved around modern JavaScript techniques and WordPress development best practices:

1. Fetching Data Using fetch()

The fetch() function was used to make asynchronous requests to the WP REST API:

fetch('https://childwebsite.com/wp-json/wp/v2/announcements', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Basic ' + btoa('username:application_password')
    },
    body: JSON.stringify({
        title: 'New Announcement',
        content: 'This is an important update.',
        status: 'publish'
    })
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));

2. Using Async/Await for API Calls

To handle API calls more efficiently, async/await was used to ensure smooth execution of the request-response cycle:

async function syncAnnouncements() {
    try {
        let response = await fetch('https://childwebsite.com/wp-json/wp/v2/announcements', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Basic ' + btoa('username:application_password')
            },
            body: JSON.stringify({
                title: 'New Announcement',
                content: 'This is an important update.',
                status: 'publish'
            })
        });
        let data = await response.json();
        console.log('Sync Success:', data);
    } catch (error) {
        console.error('Sync Error:', error);
    }
}

3. Handling WPBakery Shortcodes and HTML Encoding

Since some announcements contained WPBakery shortcodes, special HTML entities needed to be properly encoded and decoded between the master and child websites. The function below helped in encoding before transmission:

function encode_wp_shortcode($content) {
    return htmlspecialchars($content, ENT_QUOTES, 'UTF-8');
}

And on the receiving end, the content was decoded to display correctly:

function decode_wp_shortcode($content) {
    return htmlspecialchars_decode($content, ENT_QUOTES);
}

Final Outcome: Seamless Announcement Management

With this solution in place, the client was able to: ✅ Manage all announcements from a single dashboard on the parent website. ✅ Sync updates to all five websites with a single click, saving time and effort. ✅ Ensure all sites displayed the latest announcements simultaneously, reducing inconsistencies. ✅ Eliminate manual work and login hassles across multiple sites.

Conclusion: Automating Content Management in Multi-Site Environments

For WordPress businesses managing multiple sites, automation is key to reducing effort and improving efficiency. By leveraging Custom Post Types, the WP REST API, and a custom plugin, we successfully streamlined the announcement publishing process.

This approach can be adapted for various use cases beyond announcements, such as syncing product updates, blog posts, or even entire landing pages across multiple WordPress installations.

If you’re facing similar challenges with managing content across multiple WordPress sites, consider implementing a REST API-based solution—it’s a game changer! 🚀

So by end of all process, we have plugin to generate a CPT and a plugin which sync the CPT data.

Once data is sync, we used a custom short-code (which is defined in functions.php) to display CPT content on frontend, basically in menu drop-down area.

Clearing WP Rocket Cache When a REST API Post Update Occurs:

In our project, the content of a Custom Post Type (CPT) is updated via the WordPress REST API and reflected across four different domains. However, due to WP Rocket’s caching mechanism, these updates are not immediately visible on the front end.

To ensure that the latest content is displayed without requiring manual cache clearing, the client requested an automated solution to clear the entire site cache whenever a CPT post is updated via the REST API.

We achieved this by adding the following code to the functions.php file:

function my_custom_rest_post_hook($post, $request, $creating) {
    // Ensure the post is published
    if ($post->post_status !== 'publish') {
        return;
    }

    // Clear cache when the post is created or updated via REST API
    do_something_after_post_save($post);
}

add_action('rest_after_insert_offnungszeiten', 'my_custom_rest_post_hook', 10, 3);

function do_something_after_post_save($post) {
    // Ensure WP Rocket cache function exists before calling it
    if (function_exists('rocket_clean_domain')) {
        rocket_clean_domain(); // Clears entire site cache
        error_log("WP Rocket cache cleared after updating post ID: " . $post->ID);
    } else {
        error_log("WP Rocket function not found");
    }
}

This approach ensures that all four domains display the updated content without requiring manual cache purging. 🚀

Have questions or need a custom implementation? do not hesitate to connect with me. Let’s connect.