• Download
  • Contact
  • Terms of Service
  • Privacy Policy
  • About US
Codershood
  • Demos
  • Plugins
  • Angular
  • NodeJs
  • GO lang
  • Others
No Result
View All Result
Codershood
  • Demos
  • Plugins
  • Angular
  • NodeJs
  • GO lang
  • Others
No Result
View All Result
Codershood
No Result
View All Result

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

by Shashank Tiwari
August 11, 2018
in WordPress
20
3 Minutes Read
Wordpress chatroom integration using Nodejs and Socket.io 2

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.

 Download

 Demo




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,

 WordPress chatroom integration folder strcuture

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

  1. wp_enqueue_script :used to import script in wordpress.
  2. 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 blogjavascript 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.

Tags: ChatExpressNodejssocket.ioWordPressWordpress ChatWordpress Nodejs Chat
Previous Post

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

Next Post

Create a responsive wordpress theme from scratch

Related Posts

Add widget area in WordPress Theme
WordPress

Add widget area in WordPress Theme

August 11, 2018
Creating custom header wordpress
WordPress

Creating custom sidebar wordpress

August 11, 2018
creating custom header wodpress
WordPress

Creating custom header wordpress

August 11, 2018
Next Post
Create a responsive wordpress theme from scratch

Create a responsive wordpress theme from scratch

Comments 20

  1. sifan says:
    8 years ago

    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

    Reply
    • Shashank says:
      8 years ago

      Yes you are absolutely right. You can always use some encryption technique to avoid such scenarios.

      Reply
      • Win OO Mg Mg says:
        8 years ago

        What kind of encryption technique will be good ?

        Reply
        • Shashank says:
          8 years ago

          Hi,
          @winoomgmg:disqus , @lwinlwinkyi:disqus I will update this article along with data encryption. Please bear with me.

          Reply
      • Lwin Lwin Kyi says:
        8 years ago

        Hi, any idea to use What kind of encryption technique ?

        Reply
  2. Emre Kutlu says:
    8 years ago

    Thanks for this nice tutorial.
    How can we deploy this app? Do we need to use heroku or digital ocean?
    Thanks for your answer.

    Reply
    • Shashank says:
      8 years ago

      Thank you for the good words, Yes you will need a socket server and I would prefer digital ocean.

      Reply
      • Rida Noor says:
        7 years ago

        @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

        Reply
        • Shashank says:
          7 years ago

          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.

          Reply
  3. Win OO Mg Mg says:
    8 years ago

    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 ?

    Reply
    • Shashank says:
      8 years ago

      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.

      Reply
      • Win OO Mg Mg says:
        8 years ago

        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

        Reply
        • Shashank says:
          8 years ago

          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,

          Reply
  4. Ivan Petrov says:
    7 years ago

    Bro, can u tell me how i can fix this error.
    socket io faild to load…
    Error: listen EACCES 0.0.0.0:81

    Reply
    • Shashank says:
      7 years ago

      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');

      Reply
  5. Mahsa says:
    6 years ago

    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.

    Reply
    • Shashank Tiwari says:
      6 years ago

      Hi Masha, Can you please be more specific!

      Reply
      • Mahsa says:
        6 years ago

        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 🙂

        Reply
  6. Vladislav says:
    6 years ago

    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?

    Reply
  7. Parth says:
    6 years ago

    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?

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *




https://codershood.info

www.codershood.info programming blog dedicated to providing high-quality coding tutorial and articles on web development, Angular, React, Laravel, AngularJs, CSS, Node.js, ExpressJs and many more. We also provide ebook based on complicated web application along with the source code.

  • Download
  • Contact
  • Terms of Service
  • Privacy Policy
  • About US

www.codershood.info is licensed under a Creative Commons Attribution 4.0 International License.

No Result
View All Result
  • Demos
  • Plugins
  • Angular
  • NodeJs
  • GO lang
  • Others

www.codershood.info is licensed under a Creative Commons Attribution 4.0 International License.