In Integrating WordPress Chatroom using Nodejs and socket.io -part 1, we created chat-room where multiple users can talk to each other.Now in this part, we are going to integrate chatroom into WordPress.
To integrate chatroom into WordPress, we will use only client-side code i.e. HTML, CSS and Javascript.I am using twentysixteenWordPress theme. Now open twentysixteen theme folder which is located at, wp-contents/themes/
.
Below you see the folder structure of twentysixteen theme. Now create a new javascript file in the js folder of
Now create a new javascript file in the js folder of twentysixteen theme named as chat-js.js as shown below.Now copy the code of previously created chat-js file and paste it into a new chat-js.js file.
In the below Image you can see the Red Pin icon, which indicates that we are going to edit those red pin marked files. Let’s start one by one,
1. Function.php
Open function.php and Find function twentysixteen_scripts()
in function.php, when you find that function add the following line to that function.
//importing chat-js.js file by usin gwp_enqueue_script function wp_enqueue_script( 'chat-js', get_template_directory_uri() . '/js/chat-js.js', array( 'jquery' ), '20150330', true ); //creating php array $data = array("id"=>get_current_user_id()); // Passing above array to chat-js file wp_localize_script( "chat-js", "blog", $data );
Here, am using two functions
wp_enqueue_script
:used to import script in wordpress.wp_localize_script
:used to pass parameter to javascript file from php.
Here am passing $data
an array from PHP to chat-js file and in chat-js.js file am going to access that array as blog
javascript object.
Now open the chat-js.js file, In First part we were providing static user id from a chat-js.js file, Now replace that number by blog.id
.
Final chat-js.js code shown below.
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 );
2. Header.php file :
Open header.php file, add below line after,<?php wp_head(); ?>
<script src="http://localhost:81/socket.io/socket.io.js"></script>
Now save the header.php and close the file.
3. Index.php:
You can add chat room code anywhere in WordPress site.Copy the HTML code of previously created index.html and paste where ever you want.Here am adding this code in index.php file.as shown below,
Note: I have removed the rest of the code in index.php file.
<?php /** * The main template file * * This is the most generic template file in a WordPress theme * and one of the two required files for a theme (the other being style.css). * It is used to display a page when nothing more specific matches a query. * E.g., it puts together the home page when no home.php file exists. * * @link http://codex.wordpress.org/Template_Hierarchy * * @package WordPress * @subpackage Twenty_Sixteen * @since Twenty Sixteen 1.0 */ get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <div class="container" > <ul class="chatbox" id="chatbox"> <?php if(get_current_user_id()=="0"){ echo "<h2><center>Login to join chat room</center></h2>"; } ?> </ul> <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> </main><!-- .site-main --> </div><!-- .content-area --> <?php get_sidebar(); ?>
4. style.css:
Now only remaining part is CSS, which we are going to add in style.css file. So open your style.css file and the copy below code and paste it into a style.css file.
.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; }
Now open WordPress site in the browser and log in to WordPress and try to chat with other users If you can chat with other users than congratulations You have successfully integrated WordPress and chatroom using nodejs and socket.io.
If you have any queries or suggestions, please do let me know in the comment section below.
thank u very much
in Function.php you have passed the user_id to the js and the js is accessible at front-end. so it can be a security problem because user can change the id at front-end. Am I right?
thanks
Yes you are absolutely right. You can always use some encryption technique to avoid such scenarios.
What kind of encryption technique will be good ?
Hi,
@winoomgmg:disqus , @lwinlwinkyi:disqus I will update this article along with data encryption. Please bear with me.
Hi, any idea to use What kind of encryption technique ?
Thanks for this nice tutorial.
How can we deploy this app? Do we need to use heroku or digital ocean?
Thanks for your answer.
Thank you for the good words, Yes you will need a socket server and I would prefer digital ocean.
@ShankyTtiwari:disqus , thanks for this tutorial 🙂
I just want to know what if I dont want to use digital ocean? I mean what if I want to make a socket server locally? Please provide me little help about this, thanks
Hi @disqus_VzSBEgJbG4:disqus ,
You can use any server to run your Nodejs server. Just make sure that your wordpress app should able to access it online.
If am understanding this correctly, By locally you means your local machine or Localhost?
Then no, you have to host your application somewhere.
Try OpenShift online for Nodejs, they have free hosting.
Hi Shashank,
I want wordpress loged user chat each other based on the wordpress post as chat msg.
They can converse regarding wordpress post .
From the message thread , they are able to visit to the wordpress post that they are talking.
How can I do that ?
Hi Win OO Mg Mg,
You can get information about the posts and pages using wordpress datatabse table wp_posts in your nodejs part.
But your nodejs server knows nothing about on what page you are, So you have to pass the some value to the nodejs server.
Here, you can send data to nodejs server from client side javascript.
On client side javascript data comes from wordpress server now here you can use wp_localize_script.
I hope this helps you.
Hi Shashank,
a)Is it possible to link wp_post url to Chat title with href ?
(When user click while chatting , open in new tab)
The example you shows is wordpress theme.
b)Appreciate if you share how to change it to wordpress plugin ?
c)I need to install Nodes.js on the same server with wordpress host , right ?
d) Will I be able to connect and chat with the same Nodes.js/mysql wordpres server with ionic 2 ot react native or Android studio or swift iOS wordpress mobile app , correct ?
Thanks,
WO
Hi WO,
I am extremely sorry for late reply.The answers are listed below,
a). Yes it is possible you have to pass the post id to NodeJs server in order to get the details about that post, as in mentioned in my previous comment.
b) It’s in my to do list, but as of now its is on hold due to my hectic shecudle.
c) Depends, If you have VPS server than u can do this.
d) Didn’t catch you here properly. But I assuming that you are asking how this will work on mobile platform, So as long as you open this site in your application (Hybrid app), It should work properly.
Thanks,
Bro, can u tell me how i can fix this error.
socket io faild to load…
Error: listen EACCES 0.0.0.0:81
Hi there,
Please try below,
var socket = io();
or
var socket = io.connect('localhost:81');
If both doesn’t work then make sure your NodeJs server is running!
If your NodeJs server is running properly then check on which port you are running your Nodejs server. In this case, it’s port
81
, as shown below,http.listen(81,function(){
console.log("Listening on 81");
});
Then in client side, import the socket.io script.
http://localhost:81/socket.io/socket.io.js
lastly, try these,
var socket = io();
or
var socket = io.connect('localhost:81');
Hi,
Sorry, i want to see this chat everydat,
i don’t want to clear when the page is refresh.
please help me.
thank you so much.
Hi Masha, Can you please be more specific!
in fact I cant save data into database, current date that users sent message, users id that send his/her own message into page.
when I manually save some data into database, that page is show, but show ( undefined:
undefined
undefined) every parametr (nickname, message, datatime)
thank you so much 🙂
Shashank, I have a question not on the subject of this project, but I hope for your help.
I have a project, node js + WordPress.
myNode is at the root of wordpress.
Tell me, please, how, in node js, can I get the ID of the current user?
Hi, I’m just new here to learn about the sockets, Here I have followed the steps but I’m getting an error like >> http://localhost/socket.io/?EIO=3&transport=polling&t=MuxWvc6
Can you please provide any solution for this?