关于wordpress的ajax评论,已经有很多资料了,每换一个主题总要重新弄一次ajax评论。
而且前天很神奇的发现我居然没有把这东西记录下来,每次都是拿着以前的代码修修补补。。。好囧
第一次写ajax评论评论已经忘记了是参照的谁的了。。。汗一个。。。很火星的写下了这篇日志。
Xiaorsz's Blog童鞋的教程写的很完善=》关于 wordpress ajax 评论的补充和完善这次在做的时候就参考这个。可以去看一下
这里主要是以Hybrid的子主题为基础,记录一下添加过程,当然其他的主题也可以参照,个人觉得我还是写的很详细的,呵呵
OK,废话了半天开始进入正题了
既然是要用jquery,当然首先要导入jquery库,wp2.8.4已经引入了jquery的最新版本了,这个就不要我们操心了
打开你子主题的functions.php文件。写入:
define( ONE_BLUE_URL, get_stylesheet_directory_uri() );
/**
*'hybrid_head'是hybrid对header的HOOK,
*也就是把'imt_js'的结果加入生成页面的头部
*/
add_action( 'hybrid_head', 'imt_js');
/**
*'hybrid_head'是hybrid对header的HOOK,
*也就是把'imt_js'的结果加入生成页面的头部
*/
function imt_js() { ?>
<script type="text/javascript">//< ![CDATA[
var imt_mysite_url= '<?php echo ONE_BLUE_URL.'/' ?>';//子主题文件夹的URL绝对地址,记录到JS
//]]>
</script><?php
if (is_single()||is_page() && !is_page_template( 'front-page.php' )){ //判断哪些页面需要ajax评论功能。
wp_register_script('commentsajax', ONE_BLUE_URL.'/js/comments-ajax.js', false, '0.1');//文件的位置
wp_enqueue_script('commentsajax', false, false, '0.1');//引入动作控制文件
wp_register_script('blockUI', ONE_BLUE_URL.'/js/jquery.blockUI.js', false, '2.23');//文件的位置
wp_enqueue_script('blockUI', false, false, '2.23');//引入一个jquery的插件,用于美化的。
}
} ?>
OK,现在jquery库就添加进你的页面了,很简单吧,使用其他非Hybrid主题的童鞋,稍稍改一下就OK了。
上面导入了两个文件。一个是jquery.blockUI.js,这个是jquery的一个插件,可以很简单的实现很漂亮的效果,
还有一个是comments-ajax.js文件,这个是使用jquery库的具体内容如下:
$imt(document).ready(function() {
if ($imt('#commentform').length) {
$imt('#commentform').submit(function(){ //ID为 commentform 的表单提交时发生的函数,也就是整个留言输入框 form 的ID。
jQuery.ajax({
url: imt_mysite_url+'comments-ajax.php', //刚刚创建的 comments-ajax.php 文件的位置的绝对路径。
data: $imt('#commentform').serialize(),
type: 'POST',
beforeSend: function() { //post数据以前执行的动作
$imt('#reply .imt-request').remove(); //移除'#reply .imt-request'这个节点
$imt('#commentform').block({ //使用blockUI插件写出提示
message: '<img src="'+imt_mysite_url+'images/ajax-loader.gif" />正在提交评论请稍候~',
fadeIn: 1000,
fadeOut: 1000,
css: {width: '350px', top: '10px',left: '', right: '10px', border: 'none', padding: '5px', backgroundColor: '#000000', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', opacity: .6, color: '#fff',cursor:'wait' }
});
},
error: function(request) { //数据返回发生错误时,也就是非200状态,一般是500
$imt('#commentform').block({ //使用blockUI插件重新写出提示
message: '<img src="'+imt_mysite_url+'images/ajax-loader.gif" />'+request.responseText,
fadeIn: 1000, fadeOut: 1000, timeout: 5000,
showOverlay: false, centerY: false,
css: {width: '350px', top: '10px',left: '', right: '10px', border: 'none', padding: '5px', backgroundColor: '#000000', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', opacity: .6, color: '#fff',cursor:'wait' }
});
//因为blockUI插件写出的提示是转瞬即逝的,所以又加入了这样的一个东西
var imterror='<span style="color: rgb(255, 0, 0); font-size: 0.9em; font-weight: bold;">[提交失败]<span style="color: rgb(0, 0, 0); font-weight: normal; font-size: 12px;">'+request.responseText+'</span></span>';
$imt('#reply').append(imterror); //这里是要插入的位置,我插入在#reply'里面的
var imt_error=$imt('#reply .imt-request').hide();//把插入的内容隐藏起来
imt_error.fadeIn(1000); //再用一个比较好看的方式显示出插入的内容
},
success: function(data) { //数据返回正确,也就是200状态
$imt('textarea').each(function(){ //清空评论内容
this.value='';
});
$imt('#reply').append('<span style="color: rgb(0, 58, 33); font-size: 0.9em; font-weight: bold;">[提交成功]</span>');
var imt_error=$imt('#reply .imt-request').hide();
imt_error.fadeIn(1000);
if (!$imt('#comments .comment-list').length) { //检查是否是第一条评论
$imt('#respond').before('<div id="comments"><ol></ol></div>');//构建正确的DIV结构
}
$imt('#comments .comment-list').append(data); //向ID为 comments 的元素添加返回的数据,也就是整个 ol
var new_comment = $imt('#comments .comment-list li:last').hide(); //让最新添加的数据隐藏
new_comment.slideDown(1000); //再显示,这里是为了实现滑出的效果,不想要也可以直接显示
$imt('#commentform:input').attr('disabled', true);
$imt('#commentform').block({
message: '<img src="'+imt_mysite_url+'images/ajax-loader.gif" />提交成功!感谢您参与这篇日志的讨论',
fadeIn: 1500, fadeOut: 1500, imeout: 4000,
showOverlay: false, centerY: false,
css: {width: '350px', top: '10px',left: '', right: '10px', border: 'none', padding: '5px', backgroundColor: '#000000', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', opacity: .6, color: '#fff',cursor:'wait' }
});
setTimeout(function() {
$imt('#commentform:input').removeAttr('disabled');
}, 15000); //这里是设置15秒之后才可以再次留言,自行设置,单位毫秒。
}
});
return false;
});}})
注释写的比较详细了,一般应该可以看懂了吧。至少也要能看懂一个大概吧
接下来还要在子主题里面添加一个comments-ajax.php文件,用于响应我们的请求。据说这个文件几乎都是从K2主题里面抄过来的,呵呵,内容如下:
if ($_SERVER["REQUEST_METHOD"] != "POST") {
header('Allow: POST');
header("HTTP/1.1 405 Method Not Allowed");
header("Content-type: text/plain");
exit;
}
$db_check = true;
function kill_data() {
return '';
}
function check_db() {
global $wpdb, $db_check;
if($db_check) {
// Check DB
if(!$wpdb->dbh) {
echo('我们的数据库有问题。 请稍后再试。');
} else {
echo('目前,我们de站点问题。 请稍后再试。');
}
die();
}
}
ob_start('kill_data');
register_shutdown_function('check_db');
require_once(dirname(__FILE__)."/../../../wp-config.php");
$db_check = false;
ob_end_clean();
nocache_headers();
function fail($s) {
header('HTTP/1.0 500 Internal Server Error');
echo $s;
exit;
}
$comment_post_ID = (int) $_POST['comment_post_ID'];
$status = $wpdb->get_row("SELECT post_status, comment_status FROM $wpdb->posts WHERE ID = '$comment_post_ID'");
if ( empty($status->comment_status) ) {
do_action('comment_id_not_found', $comment_post_ID);
fail('在要尝试进行评论,在数据库中当前不存。');
} elseif ( 'closed' == $status->comment_status ) {
do_action('comment_closed', $comment_post_ID);
fail('对不起,这篇日志的评论系统已关闭~');
} elseif ( in_array($status->post_status, array('draft', 'pending') ) ) {
do_action('comment_on_draft', $comment_post_ID);
fail('这篇日志尚未发布,暂时不能发表评论');
}
$comment_author = trim(strip_tags($_POST['author']));
$comment_author_email = trim($_POST['email']);
$comment_author_url = trim($_POST['url']);
$comment_content = trim($_POST['comment']);
// If the user is logged in
$user = wp_get_current_user();
if ( $user->ID ) {
$comment_author = $wpdb->escape($user->display_name);
$comment_author_email = $wpdb->escape($user->user_email);
$comment_author_url = $wpdb->escape($user->user_url);
if ( current_user_can('unfiltered_html') ) {
if ( wp_create_nonce('unfiltered-html-comment_' . $comment_post_ID) != $_POST['_wp_unfiltered_html_comment'] ) {
kses_remove_filters(); // start with a clean slate
kses_init_filters(); // set up the filters
}
}
} else {
if ( get_option('comment_registration') )
fail('对不起,你必须将登录以后才能发布评论。');
}
$comment_type = '';
if ( get_option('require_name_email') && !$user->ID ) {
if ( 6> strlen($comment_author_email) || '' == $comment_author )
fail('错误:请填写必要信息(姓名和电子邮件)。');
elseif ( !is_email($comment_author_email))
fail('错误: 请输入一个有效的电子邮件地址。');
}
if ( '' == $comment_content )
fail('错误: 请填写评论内容');
// Simple duplicate check
$dupe = "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = '$comment_post_ID' AND ( comment_author = '$comment_author' ";
if ( $comment_author_email ) $dupe .= "OR comment_author_email = '$comment_author_email' ";
$dupe .= ") AND comment_content = '$comment_content' LIMIT 1";
if ( $wpdb->get_var($dupe) ) {
fail('检测到重复的评论,你已经说过 !');
}
$commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'user_ID');
$comment_id = wp_new_comment( $commentdata );
$comment = get_comment($comment_id);
if ( !$user->ID ) {
setcookie('comment_author_' . COOKIEHASH, $comment->comment_author, time() + 30000000, COOKIEPATH, COOKIE_DOMAIN);
setcookie('comment_author_email_' . COOKIEHASH, $comment->comment_author_email, time() + 30000000, COOKIEPATH, COOKIE_DOMAIN);
setcookie('comment_author_url_' . COOKIEHASH, clean_url($comment->comment_author_url), time() + 30000000, COOKIEPATH, COOKIE_DOMAIN);
}
@header('Content-type: ' . get_option('html_type') . '; charset=' . get_option('blog_charset'));
$comment->comment_type = 'comment';
$comment_index = $_POST['comment_count'] + 1;
?>
<!--200状态返回的数据,也就是你的评论样式(很明显吧,直接抄过来的只有一点细小的修改)-->
<li id="comment-<?php echo $comment->comment_ID; ?>">
<?php echo get_avatar($comment, 80); ?><div>
<div>
<cite title="<?php comment_author_url() ?>"><a title="<?php comment_author(); ?>" href="<?php comment_author_url() ?>"><?php comment_author(); ?></a></cite>
</div><!-- .comment-author .vcard -->
<abbr title="<?php comment_date( __('l, F jS, Y, g:i a', 'hybrid') ); ?>">
<?php printf( __('%1$s at %2$s', 'hybrid'), get_comment_date(), get_comment_time() ); ?>
</abbr>
<span>|</span>
<a href="<?php echo htmlspecialchars( get_comment_link( $comment->comment_ID ) ); ?>" title="<?php printf( __('Permalink to comment %1$s', 'hybrid'), $comment->comment_ID ); ?>"><?php _e('Permalink', 'hybrid'); ?></a>
<?php edit_comment_link( '<span>' . __('Edit', 'hybrid') . '', ' <span>|</span> ', '' ); ?>
</div><!-- .comment-meta-data -->
<div>
<?php comment_text(); ?>
</div><!-- .comment-text -->
<?php if ( $comment->comment_approved == '0' ) : ?>
<em><?php _e('这条评论正在等待管理员审核。。。', 'hybrid'); ?></em>
<?php endif; ?>
</li><!-- .comment -->
用Hybrid主题的童鞋,几乎可以把这个直接抄过去,其他的主题因为DIV结构估计不一样,你们自己看着comments.php文件的评论DIV结构修改吧。上面的看不懂无所谓,只要会弄最底下的评论DIV结构就可以了。
js文件我是放在一个子主题的名为js的文件夹里面的。具体的演示就是我的九个blog啦,自己看代码吧~
一共添加了三个文件:comments-ajax.php、js/jquery.blockUI.js、js/comments-ajax.js,应该还是很简单的,不是吗?没看懂?
那去写评论吧,我一点一点的回答~
已发到你QQ邮箱(156888120),谢谢~~
@koobai:已经看了,汗,你怎么知道我邮箱的。。。是你的相应文件里面就没有楼层编号。。。。。你再比对一下我的
comments-ajax.php文件吧在这么牛的任务面前,得用Safari 充充场面
看看。。
请问怎么弄那个ajax提交评论的方法,就是提交评论的时候会有一个Loading的效果~
@xiao3:
引入插件
jquery.blockUI.js,这个是jquery的一个插件,可以很简单的实现很漂亮的效果message: '<img src="'+imt_mysite_url+'images/ajax-loader.gif" />提交成功!感谢您参与这篇日志的讨论',
fadeIn: 1500, fadeOut: 1500, imeout: 4000,
showOverlay: false, centerY: false,
css: {width: '350px', top: '10px',left: '', right: '10px', border: 'none', padding: '5px', backgroundColor: '#000000', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', opacity: .6, color: '#fff',cursor:'wait' }
});
哦~这个js文件挺大的~
这个只是有一个提交Loading效果,那要是让评论提交后显示出来呢?
@xiao3:是的,如果你运用恰当,可以在很多地方引用的,你可以用参考作者写的DOME
这个也不错的。
测试一下效果~哈
试试评论看头像
看下效果,
看看
我的主题不是hybird子主题
comments-ajax.php、js/jquery.blockUI.js、js/comments-ajax.js
这几个文件放到哪里啊?????????