Обновление: кто-то ответил и предложил мне написать плагин, но на данный момент это решение намного выше моего уровня квалификации. Есть ли более простой способ?
У меня есть небольшая программа, которая использует jQuery / Ajax для взаимодействия с базой данных через php-скрипт Shoutbox.php.
Это действительно простая установка (идеально подходит для новичка, чтобы понять).
Однако я хочу поместить программу в CMS WordPress, что делает ее более сложной для меня. Кто-нибудь может дать мне совет по этим трем вопросам?
а) где бы я поместил shoutbox.php (см. Ниже) в файлы WordPress? Могу ли я добавить дополнительный файл или он будет добавлен в другой файл, например custom_functions.php?
example.com/wp-content/themes/thesis_18/custom/custom_functions.php
б) как подключиться к базе данных, откуда заканчивается shoutbox.php?
в) как бы я сослался на путь в javascript? Javascript будет в файле пользовательских функций, но тогда как мне получить путь к файлу shoutbox.php?
Код jquery перемещен в php-файл в папке плагина.
<?php
/*
Plugin Name: Shoutbox plugin
Plugin URI: http://www.eslangel.com/aboutmyplugin
Description: Shoutbox plugin
Author: Me!
Version: 1.0
Author URI: http://www.eslangel.com
*/
function my_function (){ ?>
<script type="text/javascript">
$(document).ready(function(){
//global vars
var inputUser = $("#nick");
var inputMessage = $("#message");
var loading = $("#loading");
var messageList = $(".content > ul");
//functions
function updateShoutbox(){
//just for the fade effect
messageList.hide();
loading.fadeIn();
//send the post to shoutbox.php
$.ajax({
type: "POST", url: "<?php echo $pluginDirectory = dirname(plugin_basename(__FILE__));?>/shoutbox.php", data: "action=update",
complete: function(data){
loading.fadeOut();
messageList.html(data.responseText);
messageList.fadeIn(2000);
}
});
}
//check if all fields are filled
function checkForm(){
if(inputUser.attr("value") && inputMessage.attr("value"))
return true;
else
return false;
}
//Load for the first time the shoutbox data
updateShoutbox();
//on submit event
$("#form").submit(function(){
if(checkForm()){
var nick = inputUser.attr("value");
var message = inputMessage.attr("value");
//we deactivate submit button while sending
$("#send").attr({ disabled:true, value:"Sending..." });
$("#send").blur();
//send the post to shoutbox.php
$.ajax({
type: "POST", url: "<?php echo $pluginDirectory = dirname(plugin_basename(__FILE__));?>/shoutbox.php", data: "action=insert&nick=" + nick + "&message=" + message,
complete: function(data){
messageList.html(data.responseText);
updateShoutbox();
//reactivate the send button
$("#send").attr({ disabled:false, value:"Shout it!" });
}
});
}
else alert("Please fill all fields!");
//we prevent the refresh of the page after submitting the form
return false;
});
});
</script>
<?php
}
add_action('wp_head', 'my_function');
Shoutbox.php
<?php
define("HOST", "localhost:8889");
define("USER", "root");
define("PASSWORD", "root");
define("DB", "shoutbox");
/************************
FUNCTIONS
/************************/
function connect($db, $user, $password){
$link = @mysql_connect($db, $user, $password);
if (!$link)
die("Could not connect: ".mysql_error());
else{
$db = mysql_select_db(DB);
if(!$db)
die("Could not select database: ".mysql_error());
else return $link;
}
}
function getContent($link, $num){
$res = @mysql_query("SELECT date, user, message FROM shoutbox ORDER BY date DESC LIMIT ".$num, $link);
if(!$res)
die("Error: ".mysql_error());
else
return $res;
}
function insertMessage($user, $message){
$query = sprintf("INSERT INTO shoutbox(user, message) VALUES('%s', '%s');", mysql_real_escape_string(strip_tags($user)), mysql_real_escape_string(strip_tags($message)));
$res = @mysql_query($query);
if(!$res)
die("Error: ".mysql_error());
else
return $res;
}
/******************************
MANAGE REQUESTS
/******************************/
if(!$_POST['action']){
//We are redirecting people to our shoutbox page if they try to enter in our shoutbox.php
header ("Location: index.html");
}
else{
$link = connect(HOST, USER, PASSWORD);
switch($_POST['action']){
case "update":
$res = getContent($link, 20);
while($row = mysql_fetch_array($res)){
$result .= "<li><strong>".$row['user']."</strong><img src=\"css/images/bullet.gif\" alt=\"-\" />".$row['message']." <span class=\"date\">".$row['date']."</span></li>";
}
echo $result;
break;
case "insert":
echo insertMessage($_POST['nick'], $_POST['message']);
break;
}
mysql_close($link);
}
Я взял html со своей страницы index.html в исходном приложении и поместил ее в текстовый виджет на боковой панели.
<a id="logo" title="Go to eslangel!" href="http://www.eslangel.com"><img src="http://eslangel.com/wp-content/plugins/myplugin/css/images/logo.jpg" alt="eslangel.com" /></a>
<form method="post" id="form">
<table>
<tr>
<td><label>User</label></td>
<td><input class="text user" id="nick" type="text" MAXLENGTH="25" /></td>
</tr>
<tr>
<td><label>Message</label></td>
<td><input class="text" id="message" type="text" MAXLENGTH="255" /></td>
</tr>
<tr>
<td></td>
<td><input id="send" type="submit" value="Shout it!" /></td>
</tr>
</table>
</form>
<div id="container">
<ul class="menu">
<li>Shoutbox</li>
</ul>
<span class="clear"></span>
<div class="content">
<h1>Latest Messages</h1>
<div id="loading"><img src="http://eslangel.com/wp-content/plugins/myplugin/css/images/loading.gif" alt="Loading..." /></div>
<ul>
<ul>
</div>
</div>