我如何将这个ajax程序移动到wordpress



更新:有人回答并建议我写一个插件,但这是一个解决方案,远远超出了我的技能水平。有更简单的方法吗?

我有一个小程序,使用jQuery/Ajax通过php脚本与数据库进行交互。

这是一个非常简单的设置(非常适合新手理解)。

然而,我想把程序放在WordPress CMS中,这对我来说更复杂。对于这三个问题,谁能给我一些建议?

a)我应该把shoubox .php(见下文)放在wordpress文件的哪里?我是否可以添加一个额外的文件,或者放在另一个文件中,比如custom_functions。php?

example.com/wp-content/themes/thesis_18/custom/custom_functions.php

b)如何连接到数据库从哪里shoubox .php结束?

c)我如何在javascript中引用路径?javascript将在一个自定义函数文件,但我如何得到路径到哪里的shoubox .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);
}

我从原始应用程序的index.html页面中取出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>  

我会创建一个插件。这是非常有用的,原因如下

  1. 可以很容易地打开和关闭。因此,它可以快速分发或版本控制用于测试目的。
  2. 你可以沙箱化它,这样它就不会干扰Wordpress。这可以让你看看它是否会破坏WP(可能在更新之后)
  3. 插件可以访问特殊功能。比如问WP你的插件目录是什么。现在你可以在不同的站点之间移动插件,路径不会中断。

阅读更多关于Wordpress插件开发的内容!http://codex.wordpress.org/Writing_a_Plugin

创建一个插件实际上很容易。只需要找到位于wp-content目录下的plugins文件夹,并创建一个新文件夹。在其中放置一个myplugin.php文件,并在顶部添加以下注释结构

/*
Plugin Name: Shoutbox plugin
Plugin URI: http://www.mywebsite.com/aboutmyplugin
Description: Shoutbox plugin
Author: Me!
Version: 1.0
Author URI: http://www.mywebsite.com
*/

将shoutbox.php也复制到这个文件夹中。不要包含上面的标题信息。

在你的主文件中,现在你只需要做两件事。
  1. 通过在myplugin.php -

    add_action('wp_head', 'my_function');
    function my_function() { 
      //your javascript from above. make sure it is php escaped
    }
    
  2. 将ajax位指向shoutbox.php文件,以便它可以做它的事情。

    //change
    url: "shoutbox.php"
    //to
    <?php $pluginDirectory = dirname(plugin_basename(__FILE__)); ?>
    url: <?php $pluginDirectory + /shoutbox.php; ?>
    

确保你从wordpress网站的插件页面激活你的插件。这整个序列的作用是:

    创建插件
  1. 将javascript注入到每个wordpress页面的顶部
  2. 动态修改javascript,以便它可以在插件目录中找到shoutbox.php的位置。

相关内容

最新更新