Integrating WordPress Chatroom using nodejs and socket.io -part 1

Last time I published Private chatting application where a single user can talk each other and Here We are implementing a chatroom using Nodejs and Socket.io in WordPress. You might have seen many websites use plugins for real-time chatting system Actually, it is very easy to  Integrate WordPress and Chatroom using Nodejs and socket.io.

I would not say this only the way to do it but the easiest way I have found so far and If you want integration chat room in WordPress  than the more permanent solution would be to make a plugin.

The outcome is shown below,

 WordPress chatroom integration using Nodejs and Socket.io example

 

This article consists of two component, first is building chat room using Nodejs and Socket.io and In second part covers the Integration of WordPress and chat room. Here am using Database of WordPress to keep track of users so I assume you have pro-efficient experience in WordPress, like how WordPress works, how to install and customize the WordPress site.

This article seems little lengthy So I have divided into two parts, Building chat room using Nodejs and Socket.io is covered in the first part  and the second part covers the Integration of a chat room in WordPress.

But Before creating chat room lets create a table to store messages sent by users.

When you install WordPress you give a name of the Database. So in that database, you have to create a table or alternatively, you can find your database  name in wp-config.php. find the below line,

define('DB_NAME', 'My_DB_Name');

Now select that Database and Run the below queries,
SQL queries:

USE WordPressChat;

CREATE TABLE IF NOT EXISTS `message` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `messages`  text NOT NULL,
  `uid` varchar(11) NOT NULL,
  `name` varchar(20) NOT NULL,
  `time` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
);

As we are using Database of WordPress to get information of the user and  for now, we  are using wp_usermeta table, where wp is prefix  selected by the time of installing WordPress. The column name of wp_usermeta table listed below and we are using two columns user_id and meta_value.

To retrieve the username from meta_value column and to use session id we are using wp_usermeta.

Wordpress chatroom column name

Now you have created your table to store messages and understood from where you will authenticate logged in WordPress user.Now  it's time to create chatroom using nodejs and Socket.io.

Making chat room using Nodejs and Socket.io

On Nodejs server, we will use a server.js file to send and receive the messages by using socket.io and to store messages we will use MYSQL node_module.

Here you have to connect Nodejs to WordPress database by providing proper credentials.Now If you are doing this on your local machine (localhost) then just provide localhost as a hostname. But if you are doing this on the server, follow these steps:

  1. Find out the IP of your MYSQL host and IP of your Nodejs server.
  2. Go to remote MySql section in Cpanel of your PHP hosting and add  the IP of your Nodejs server after this step MYSQL host will allow your Nodejs server to connect to Database.
  3. Now on Nodejs server, In the server.js file, you need to provide the IP of your MYSQL host to connect WordPress Database.

Now after doing these steps, you are ready to create your Nodejs application.

package.json :

{
  "dependencies": {
    "express": "4.13.3",
    "body-parser": "1.14.1",
    "socket.io": "1.3.7",
    "mysql": "2.9.0",
    "dateformat": "1.0.12",
  }
}

Now, create a file named index.html file. This file contains, the layout to display messages and a text box to send a message to a server as shown below.

index.html : 

<html >
  <head>
    <title>Real time Chat Room </title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <style type="text/css">
      .container{
        height: 100%;
        font-family: Montserrat, "Helvetica Neue", sans-serif;
      }
      .chatbox{
        width: 100%;
        height: 350px;
        overflow-y:scroll;
        background: rgba(146, 121, 110, 0.26);
        border-radius: 0px;
          border: solid 1px #BDBDBD;
          padding-left: 15px;
          padding-right: 15px;
          padding-bottom: 15px;
          margin: 0px !important;
      }
      .chatbox li{
        clear: both;
        margin-bottom: 10px;
        text-decoration: none;
        list-style-type: none;
        margin: 20px 0px 0px 20px;
      }
      .actual_msg{
        float: left;
        display: inline-block;
        margin-right: 20px;
        padding: 25px 34px;
        min-width: 160px;
        min-height: 10px;
        max-width: 510px;
        border-radius: 5px;
        box-shadow: 0px 3px 3px rgba(172, 172, 172, 0.73);
        line-height: 1.4;
        word-wrap: break-word;
        color: #1A1A1A;
        background-color: rgba(0, 0, 0, 0.11);        
      }
      .date{
          font-size: 9px;
          float: left;
          margin-top: 10px;
      }
    </style>
  </head>
  <body>
    <div class="container" >
      <div class="chatbox" id="chatbox">

      </div>
      <br/>
      <div id="name-group" class="form-group">
        <textarea class="form-control msg_box" id="msg_box" placeholder="Type here and check the Title in Tab"></textarea>
      </div>
    </div>
  </body> 
  
  <script src="/socket.io/socket.io.js"></script>
  <script src="js/jquery.min.js"></script>
  <script src="js/script.js"></script>
</html>

Now create another file named as chat-js.js and paste the code below code.This file contains methods to send, receive messages socket respectively and also take care of appending messages to the layout.

chat-js.js :

( function( $ ) {
    var socket = io();
    var uid=1;
	socket.emit('validate',uid);
	
	$('.msg_box').keypress(function(event){

		if ( event.which == 13 ) {        
        	data={
        		id:uid,
        		msg:$("#msg_box").val()
	        };
	        socket.emit('send msg',data);
            $("#msg_box").val('');
        }
    });

	socket.on('user entrance',function(data){
		if(uid!="0"){
			$("#chatbox").append("<div class='col-xs-12'><h2><center>"+data.info+"</center></h2></div>");
			console.log(data.message);
			for(var i=0;i<data.message.length;i++){
				if(data.message[i]['uid']==uid){
					$("#chatbox").append("<li class='actual_msg' style='text-align:right;float:right'><section><strong style='margin-right: -15px;'>You:</strong><br>"+data.message[i].messages+"</section><span class='date'>"+data.message[i].time+"</span></li>"); 
				}else{
					$("#chatbox").append("<li class='actual_msg' style='text-align:left;float:left'><section><strong style='margin-left: -15px;'>"+data.message[i].name+": </strong><br>"+data.message[i].messages+"</section><span class='date'>"+data.message[i].time+"</span></li>"); 
				}
			}
			$("#chatbox").animate({scrollTop: $("#chatbox").get(0).scrollHeight},900);			
		}		 
	}); 

	socket.on('exit',function(data){
	    if((data.message).trim()!="undefined"){
	    	$("#chatbox").append("<div class='col-xs-12'><h2><center>"+data.message+" is offline</center></h2></div>");
	    }
	});

	socket.on('get msg',function(data){
		//to scroll the div
		$("#chatbox").animate({scrollTop: $("#chatbox").get(0).scrollHeight},900);
		if(data.id==uid){
			$("#chatbox").append("<li class='actual_msg' style='text-align:right;float:right'><section><strong style='margin-right: -15px;'>You:</strong><br>"+data.message+"</section><span class='date'>"+data.date+"</span></li>"); 
		}else{
		    $("#chatbox").append("<li class='actual_msg' style='text-align:left;float:left'><section><strong style='margin-left: -15px;'>"+data.user+": </strong><br>"+data.message+"</section><span class='date'>"+data.date+"</span></li>"); 
		}
	});

} )( jQuery );

Now you might have noticed that I am giving  uid=1; let me explain,

we don't have our own login system So by default we are using WordPress login system. In WordPress, The Site owner (Admin) always has User Id as 1. You can find in all user's id in wp_users table. If you want to create your own login system please read this article.Here we are using WordPress login system so we are creating login and register page.

Before running this application create another user in WordPress user and provide the id of that user in chat-js.js script.

Now run the application, and now you are able to chat with other users.

In the second part, we will integrate this chat room to WordPress.