Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Using socket.io to implement live notifications on my WordPress site


Using socket.io to implement live notifications on my WordPress site


To use Socket.IO to implement live notifications on your WordPress site, follow these steps:

1. Install Required Packages:
- Install Node.js and npm on your machine.
- Install Socket.IO and Redis using npm:

bash
     npm install socket.io redis
     

2. Set Up WordPress:
- Ensure that WordPress is configured to use the WordPress REST API.

3. Create a Node.js Server:
- Create a new Node.js project using a framework like Express.js.
- Set up the server to listen for incoming requests.
- Use the WordPress REST API to fetch data from WordPress.

4. Handle Real-Time Updates:
- Use Socket.IO to establish real-time communication between the Node.js server and the client.
- Implement event listeners to handle updates in real-time.
- Use the WordPress REST API to fetch updated data and broadcast it to connected clients.

5. Configure Socket.IO:
- Add the following constants to `wp-config.php` to configure Liveblog plugin to use WebSockets:

php
     define('LIVEBLOG_USE_SOCKETIO', true);
     define('LIVEBLOG_SOCKETIO_URL', 'https://your-site.com:3000');
     define('LIVEBLOG_REDIS_HOST', 'localhost');
     define('LIVEBLOG_REDIS_PORT', 6379);
     

6. Run the Socket.io Server:
- Run the Socket.io server using Node.js:

bash
     node nodeapp/app.js
     

7. Test Real-Time Notifications:
- Open a Liveblog post in two different browser windows and check that whenever a user changes the list of entries in one window, the list in the other window is refreshed in real-time.

Here is an example of how you can use Socket.IO to implement live notifications on your WordPress site:


//javascript
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);

// Set up the WordPress REST API endpoint
const wordpressApiUrl = 'https://your-wordpress-site.com/wp-json/wp/v2/posts';

// Make a GET request to fetch posts
axios.get(wordpressApiUrl)
  .then((response) => {
    // Handle the response data
    const posts = response.data;
    console.log(posts);
  })
  .catch((error) => {
    console.error('Error fetching posts:', error);
  });

// Handle real-time updates
io.on('connection', (socket) => {
  console.log('A user connected');

  // Handle new posts
  socket.on('new-post', (post) => {
    // Fetch the new post from WordPress
    axios.post(wordpressApiUrl, post)
      .then((response) => {
        // Broadcast the new post to all connected clients
        io.emit('new-post', response.data);
      })
      .catch((error) => {
        console.error('Error creating new post:', error);
      });
  });

  // Handle updated posts
  socket.on('update-post', (post) => {
    // Fetch the updated post from WordPress
    axios.put(wordpressApiUrl, post)
      .then((response) => {
        // Broadcast the updated post to all connected clients
        io.emit('update-post', response.data);
      })
      .catch((error) => {
        console.error('Error updating post:', error);
      });
  });

  // Handle deleted posts
  socket.on('delete-post', (post) => {
    // Fetch the deleted post from WordPress
    axios.delete(wordpressApiUrl, post)
      .then((response) => {
        // Broadcast the deleted post to all connected clients
        io.emit('delete-post', response.data);
      })
      .catch((error) => {
        console.error('Error deleting post:', error);
      });
  });

  // Handle disconnections
  socket.on('disconnect', () => {
    console.log('A user disconnected');
  });
});

// Start the server
const port = 3000;
server.listen(port, () => {
  console.log(`Node.js server is running on port ${port}`);
});

This example sets up a Node.js server that listens for incoming connections and handles real-time updates using Socket.IO. It fetches data from the WordPress REST API and broadcasts updates to connected clients.

Citations:
[1] https://github.com/Automattic/liveblog
[2] https://www.optimalvirtualemployee.com/blog/implementing-real-time-notification-using-socket-io-and-node-js/
[3] https://crowdforthink.com/blogs/how-to-implement-real-time-notification-using-socketio-and-nodejs
[4] https://stackoverflow.com/questions/11550103/push-notifications-using-socket-io-and-php
[5] https://www.youtube.com/watch?v=j_duwpvkldg