为主题添加AJAX提交评论功能的php代码-wordpress

教程大全 2026-01-08 07:09:20 浏览

首先需要在主题的function.php文件里添加一段函数:

复制代码

代码如下:

< ?phpfunction fail($s) {header('HTTP/1.0 500 Internal Server Error');echo $s;exit;}function ajax_comment(){if($_POST['action'] == 'ajax_comment') {global $wpdb, $db_check;// Check DBif(!$wpdb->dbh) {echo('Ourblog_charset'));?>//这里需要粘贴你的评论框架代码,不过相关的调用代码有所变化://评论ID:$comment->comment_ID//评论者名字:$comment->comment_author//判断评论者是否填写了网站地址:$comment->get_comment_author_url//评论者URL:$comment->comment_author_url//评论时间:mysql2Date(__('F jS, Y'),$comment->comment_date)//评论者e-mail:$comment->comment_author_email//评论内容$comment->comment_content< ?phpdie();}}add_action('init', 'ajax_comment');//添加AJAX评论钩子?>

如果处理评论内容里的换行符的话,$comment->comment_content需做以下处理:

复制代码

代码如下:

< ?php$aj_order = array("\r\n", "\n", "\r");$aj_comment_content = str_replace($aj_order,'',$comment->comment_content);echo $aj_comment_content;?>

用jQuery写提交评论时的脚本,这也是关键的部分:

复制代码

代码如下:

为主题添加AJAX提交评论功能的php代码

jQuery(document).ready(function() {if (jQuery('#commentform').length) {jQuery('#commentform').subMIT(function(){ //ID为 commentform 的表单提交时发生的函数,也就是整个留言输入框 form 的ID。var ajaxCommentsURL = WINdow.location.href;jQuery.ajax({url: ajaxCommentsURL,data: jQuery('#commentform').serialize()+'&action=ajax_comment',type: 'POST',beforeSend: function() {jQuery('#commenterror').hide();var submit='Submitting Comment...

'; //创建名为 submit 的字符串,稍后插入,这里的样式大家自己根据需要定义,那个背景图片自己去下哈。var error='
Posted comment fail.
'; //创建名为 error 的字符串jQuery('#comments').after(submit); // 在ID为 comments 的元素后插入刚定义的 submitjQuery('#comments').after(error); // 同样插入刚定义的 errorjQuery('#commentload').slideDown(); // 让submit 向下滑出},error: function(request) { //发生错误时jQuery('#commentload').hide(); //隐藏 submitjQuery('#commenterror').SHOW("slow").html(request.responseText); //显示 error},success: function(data) {jQuery('textarea').each(function(){this.value='';});jQuery('#commenterror').hide().html();if (!jQuery('#thecomments').length) {jQuery('#pinglist').before('
    ');}jQuery('#thecomments').Append(data); //向ID为 thecomments 的元素添加数据,也就是整个 ol 或 ulvar new_comment = jQuery('#thecomments li:last').hide(); //让最新添加的数据隐藏new_comment.slideDown(1000); //再显示,这里是为了实现滑出的效果,不想要也可以直接显示jQuery('#commentform:input').attr('disabled', true);jQuery('#commentload').slideUp("slow");jQuery('#messagebox').slideUp("slow"); //这是针对我模版而加的,因为我模版在没有留言时会有个 nocomment 的元素,我要让添加一条留言后他自动隐藏,要不然会矛盾,呵呵,这个可以自行选择要或不要setTimeout(function() {jQuery('#commentform:input').removeAttr('disabled');}, 10000); //这里是设置10秒之后才可以再次留言,自行设置,单位毫秒。}});return false;} );}})

    脚本里的对象ID要对应主题里的评论相关框架的ID。 AJAX提交后的评论序号显示为1。

    本文版权声明本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请联系本站客服,一经查实,本站将立刻删除。

    发表评论

    热门推荐