AjaxChat WordPress Integration

This integration have been tested with Ajax Chat v 0.8.7 and WordPress 3.8.1,

It has the following features:

  • Auto login.
  • Administration based on WordPress management system.
  • Admin and Moderation based on WordPress system, Admin->install_plugins,
    Moderator->edit_published_post or Moderator->edit_posts.
  • Nickname in use.
  • Ajax Chat form integration with word press.

Previous integration is deprecated, it shouldn’t work with newer Ajax Chat and WordPress versions.

No core file has been touched from standalone Ajax Chat but the custom files needed to integrate..
The code is cleaner and easy to read and maintain..

You will have the option to download the integration and read and or edit tru the tutorial.


Download the file and uncompress chat folder in your WordPress folder root installation, then install as usual, read installation steps in readme file in the chat folder.

Using the tutorial:
This tutorial was done using the normal installation of WordPress, the following installation structure must be consider:

  • All WordPress file resides in the web folder
  • Ajax Chat files and folders are placed in a folder called “chat“, this folder resides along with WordPress files and folders.

Lets get down to editing now.

Open custom.php located in ‘/lib’ folder in your ‘chat‘ folder, we are going to add the following code:

 * @package AJAX_Chat
 * @author Sebastian Tschan
 * @copyright (c) Sebastian Tschan
 * @license Modified MIT License
 * @link
 * WordPress integration
 * @author  Neumann Valle
 * @link

// Include custom libraries and initialization code here
	// init WordPress
	if( isset( $_SERVER['DOCUMENT_ROOT'] ) ){
		$file	= $_SERVER['DOCUMENT_ROOT'].'wp-config.php';
		if( !file_exists( $file ) ){
			exit( ' couldn\'t be found in your WordPress installation, please fix $file variable with correct one.');
			exit( 'your server could be misconfigurated , DOCUMENT_ROOT was not available in server globals.' );
	// require wp-config.php
	require_once( $file );
	// initiate $current_user var
	global $current_user;

That should be sufficient to require our WordPress initiation vars and functions, if you get an error like.
wp-config.php couldn’t be found in your WordPress installation, please fix $file variable with correct one.

Check and fix your require path in $file variable, eg, if you have WordPress installed in /blog folder then you need to fix the path like this.

$file	= $_SERVER['DOCUMENT_ROOT'].'blog/'.'wp-config.php';

That should help, if it doesn’t and you get a different error then make sure your $_SERVER vars are correctly set in your server..

Now that custom.php is out of the way, open CustomAJAXChat.php located in ‘/lib/clasess/’ folder, lets do it easy remember that we are working on AjaxChat v 0.8.7 , delete all its content and copy paste this code onto the file.

 * @package AJAX_Chat
 * @author Sebastian Tschan
 * @copyright (c) Sebastian Tschan
 * @license Modified MIT License
 * @link
 * WordPress integration
 * @author  Neumann Valle
 * @link

class CustomAJAXChat extends AJAXChat {

	function initCustomRequestVars(){
		if( !$this->getRequestVar('logout') && is_user_logged_in() ) {
			$this->setRequestVar('login', true);
	 * Returns an associative array containing userName, userID and userRole
	 * Returns guest login if null
	function getValidLoginUserData() {
		// globalize the important variables from WP
		global $current_user;
		// Check if we have a valid registered user:
		$customUsers = $this->getCustomUsers();
		if( isset( $current_user ) && is_user_logged_in() ){
			$userData 				= 	array();
			$userData['userID']		=	$current_user->data->ID;
			$userData['userName']	=	$this->trimUserName( $current_user->data->display_name );
			if( current_user_can('install_plugins') ){
				$userData['userRole'] = AJAX_CHAT_ADMIN;
			}else if( current_user_can('edit_published_posts') || 
						current_user_can('edit_posts') ){ 
				$userData['userRole'] = AJAX_CHAT_MODERATOR;
				$userData['userRole'] = AJAX_CHAT_USER;
			//echo '<script>console.log('.json_encode( $userData ).')</script>';
			return $userData;
		if( $this->getRequestVar('password') ) {
				$userName = $this->getRequestVar('userName');
				$userName = $this->convertEncoding($userName, $this->getConfig('contentEncoding'), $this->getConfig('sourceEncoding'));
				$password = $this->getRequestVar('password');
				$password = $this->convertEncoding($password, $this->getConfig('contentEncoding'), $this->getConfig('sourceEncoding'));
				foreach( $customUsers as $key => $value ) {
					if( ($value['userName'] == $userName) && ($value['password'] == $password) ) {
						$userData = array();
						$userData['userID'] = $key;
						$userData['userName'] = $this->trimUserName($value['userName']);
						$userData['userRole'] = $value['userRole'];
						return $userData;
				return null;
				// Guest users:
				return $this->getGuestUser();
	function getGuestUser() {
		return null;
		if($this->getConfig('allowGuestUserName')) {
			$maxLength =	$this->getConfig('userNameMaxLength')
			- $this->stringLength($this->getConfig('guestUserPrefix'))
			- $this->stringLength($this->getConfig('guestUserSuffix'));
			$userName	=$this->getRequestVar('userName');
			// Trim guest userName:
			$userName = $this->trimString($this->getRequestVar('userName'), null, $maxLength, true, true);
			// check if usernick choosen as guest is in the WP database.. if its is Deny access.
			if( username_exists( $userName ) ){
				return null;
			// If given userName is invalid, create one:
			if(!$userName) {
				$userName = $this->createGuestUserName();
			} else {
				// Add the guest users prefix and suffix to the given userName:
				$userName = $this->getConfig('guestUserPrefix').$userName.$this->getConfig('guestUserSuffix');	
		} else {
			$userName = $this->createGuestUserName();
		$userData = array();
		$userData['userID'] = $this->createGuestUserID();
		$userData['userName'] = $userName;
		$userData['userRole'] = AJAX_CHAT_GUEST;
		return $userData;		
	 * Store the channels the current user has access to
	 * Make sure channel names don't contain any whitespace
	function &getChannels() {
		if($this->_channels === null) {
			$this->_channels = array();
			$customUsers = $this->getCustomUsers();
			// Get the channels, the user has access to:
			if($this->getUserRole() == AJAX_CHAT_GUEST) {
				$validChannels = $customUsers[0]['channels'];
			} else {
				//$validChannels = $customUsers[$this->getUserID()]['channels'];
				$validChannels = $customUsers[0]['channels'];
			// Add the valid channels to the channel list (the defaultChannelID is always valid):
			foreach($this->getAllChannels() as $key=>$value) {
				if ($value == $this->getConfig('defaultChannelID')) {
					$this->_channels[$key] = $value;
				// Check if we have to limit the available channels:
				if($this->getConfig('limitChannelList') && !in_array($value, $this->getConfig('limitChannelList'))) {
				if(in_array($value, $validChannels)) {
					$this->_channels[$key] = $value;
		return $this->_channels;

	// Store all existing channels
	// Make sure channel names don't contain any whitespace
	function &getAllChannels() {
		if($this->_allChannels === null) {
			// Get all existing channels:
			$customChannels = $this->getCustomChannels();
			$defaultChannelFound = false;
			foreach($customChannels as $name=>$id) {
				$this->_allChannels[$this->trimChannelName($name)] = $id;
				if($id == $this->getConfig('defaultChannelID')) {
					$defaultChannelFound = true;
			if(!$defaultChannelFound) {
				// Add the default channel as first array element to the channel list
				// First remove it in case it appeard under a different ID
				$this->_allChannels = array_merge(
		return $this->_allChannels;

	function &getCustomUsers() {
		// List containing the registered chat users:
		$users = null;
		return $users;
	function getCustomChannels() {
		// List containing the custom channels:
		$channels = null;
		// Channel array structure should be:
		// ChannelName => ChannelID
		return array_flip($channels);


Make sure you pasted it correctly… save it and let’s continue with the tutorial.

Now open the document loggedOut.html located in ‘/lib/template/’ folder, do the same process as in previous file, delete all its content and paste the following onto it..

<?xml version="1.0" encoding="[CONTENT_ENCODING/]"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">
<html xmlns="" xml:lang="[LANG_CODE/]" lang="[LANG_CODE/]" dir="[BASE_DIRECTION/]">

	<meta http-equiv="Content-Type" content="[CONTENT_TYPE/]" />
	<style type="text/css">
		body {
	<!--[if lt IE 7]>
		<link rel="stylesheet" type="text/css" href="css/ie5-6.css"/>
	<script src="js/chat.js" type="text/javascript" charset="UTF-8"></script>
	<script src="js/lang/[LANG_CODE/].js" type="text/javascript" charset="UTF-8"></script>
	<script src="js/config.js" type="text/javascript" charset="UTF-8"></script>
	<script type="text/javascript">
		// <![CDATA[
			function initializeLoginPage() {
				if(!ajaxChat.isCookieEnabled()) {
					var node = document.createElement('div');
					var text = document.createTextNode(ajaxChatLang['errorCookiesRequired']);
				// set action post and redirect to, wordpress integration
			// set wordpress specifics
			function ajaxChat_loginform(){
			var loginForm	=	document.getElementById('loginForm');
				if( typeof loginForm === 'object' ){
					loginForm.action 						= ajaxChatConfig.wplogin_path;
					loginForm.elements['redirect_to'].value = ajaxChatConfig.afterwpLoginRedirect;
			ajaxChatConfig.sessionName = '[SESSION_NAME/]';
			ajaxChatConfig.cookieExpiration = parseInt('[COOKIE_EXPIRATION/]');
			ajaxChatConfig.cookiePath = '[COOKIE_PATH/]';
			ajaxChatConfig.cookieDomain = '[COOKIE_DOMAIN/]';
			ajaxChatConfig.cookieSecure = '[COOKIE_SECURE/]';

			ajaxChat.init(ajaxChatConfig, ajaxChatLang, true, true, false);
		// ]]>
	<script type="text/javascript">
		// <![CDATA[
		function handleLogin() {
			var loginForm = document.getElementById('loginForm');
			var userNameField = document.getElementById('userNameField');
			var passwordField = document.getElementById('passwordField');
			var channelField = document.getElementById('channelField');
			var redirectField = document.getElementById('redirectField');
			if(passwordField.value.length == 0) {
				loginForm.setAttribute('action', '[LOGIN_URL/]');
				userNameField.setAttribute('name', 'userName');
			} else {
				var channelRequest = 'channelName=' + encodeURIComponent(channelField.value);
				var regExp = /\?/;
				if(regExp.test(redirectField.value)) {
					redirectField.value += '&';
				} else {
					redirectField.value += '?';
				redirectField.value += channelRequest;
			return true;
		// ]]>

<body onload="initializeLoginPage();">
	<div id="loginContent">
		<div id="loginHeadlineContainer">
		<form id="loginForm" action="" method="post" enctype="application/x-www-form-urlencoded" onsubmit="return handleLogin();">
			<div id="loginFormContainer">
				<input type="hidden" name="login" id="loginField" value="login"/>
				<input type="hidden" name="redirect" id="redirectField" value="[REDIRECT_URL/]"/>
				<div><label for="userNameField">[LANG]userName[/LANG]:</label><br />
				<input type="text" name="log" id="userNameField" maxlength="[USER_NAME_MAX_LENGTH/]"/></div>
				<div><label for="passwordField">[LANG]password[/LANG]*:</label><br />
				<input type="password" name="pwd" id="passwordField"/></div>
				<div><label><input name="rememberme" type="checkbox" id="rememberme" value="forever" tabindex="90" /> Remember Me?</label></div>
				<div><label for="channelField">[LANG]channel[/LANG]:</label><br />
				<select name="channelName" id="channelField">[CHANNEL_OPTIONS/]</select></div>
				<div><label for="languageSelection">[LANG]language[/LANG]:</label><br />
				<select id="languageSelection" name="lang" onchange="ajaxChat.switchLanguage(this.value);">[LANGUAGE_OPTIONS/]</select></div>
				<div><input type="submit" name="submit" id="loginButton" value="[LANG]login[/LANG]"/></div>
				<div><input type="hidden" name="redirect_to" value="" /></div>
				<div id="loginRegisteredUsers">* [LANG]registeredUsers[/LANG]</div>
		<div id="errorContainer">[ERROR_MESSAGES/]<noscript><div>[LANG]requiresJavaScript[/LANG]</div></noscript></div>
			Please retain the full copyright notice below including the link to
			This not only gives respect to the amount of time given freely by the developer
			but also helps build interest, traffic and use of AJAX Chat.
			Sebastian Tschan
			Ajax integration with WordPress
			Neumann Valle
		<div id="copyright"><a href="">AJAX Chat</a> &copy; <a href=""></a></div>


This last edit is really important because it has new code that logins against WordPress , ‘wp-login.php‘ which authenticates and set credentials, if the user tries a name registered and want to use as guest nickname will get an error the name is invalid, but if he tries his/her WordPress credential it will be logged in and redirected to the chat..

Last but not least open config.js located in the JS folder of ‘chat‘ find the following var:

// The base URL of the chat directory, used to retrieve media files (images, sound files, etc.):
	baseURL: './'

After that variable paste the following without touching any other var:

	// base url where your wp-login.php reside that is used for the login ajax login form
	wplogin_path : '../../wp-login.php',
	// url where the browser should redirect after a sucessful login to wordpress
	afterwpLoginRedirect: 'chat/',

This two new var tells the login form where to POST and to redirect after a successful authentication in WordPress.

wplogin_path : '../../wp-login.php',

Tells the action form and where wp-login.php is located, fix it if your installations isn’t the same as the tutorial.

afterwpLoginRedirect: 'chat/',

Tells where to redirect after the login succeed , replace it with the path of your chat folder..

and that’s it, install the chat as directed in the read me file.

You found bugs post them here.. comments welcome.

14 comments for “AjaxChat WordPress Integration

  1. evora
    1 March 2014 at 15:36 pm

    it is possible to embed torrent trader please

  2. UTAN
    2 March 2014 at 14:31 pm


    Yes it is possible but I don’t have a copy of that forum board..

  3. evora
    3 March 2014 at 1:26 am
  4. filmvf
    19 April 2014 at 10:02 am

    thanks man

  5. Xiphi
    4 June 2014 at 6:54 am

    my wordpress is in root (public_html) and i want to install this in a subdomain.
    may you help me do it?

  6. Joseph
    26 September 2014 at 4:24 am

    How do you add additional channels for users?

  7. Eugenio
    31 October 2014 at 2:29 am

    Great work Neumann!

    How can I customize the number and the name of new chat channels?

    Thanks for your work

  8. Rigo
    27 January 2015 at 19:39 pm

    How do you change or ADD more years in chat logs for admins?

  9. Svend Rugaard
    17 October 2015 at 11:47 am

    I cant get this to work it constantly say couldn’t be found in your WordPress installation, please fix $file variable with correct one.

  10. intelboard
    30 May 2016 at 14:30 pm

    Query: SELECT userID, userName, userRole, channel, UNIX_TIMESTAMP(dateTime) AS timeStamp, ip FROM `u697320866_ubare`.ajax_chat_online ORDER BY userName; Error-Report: Table ‘u697320866_ubare.ajax_chat_online’ doesn’t exist Error-Code: 1146

    That’s the error I get.

  11. falconCoin
    27 February 2017 at 22:16 pm

    is this still possible to be used?

  12. Botyyy
    17 December 2017 at 15:47 pm

    The shoutbox seems out of date on my side. I had no problem for atleast 2 years but now I’m log out every time after each action on my site 🙁

Leave a Reply

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


This site uses Akismet to reduce spam. Learn how your comment data is processed.