存档

文章标签 ‘非插件’

iNove主题非插件利用jQuery实现Ajax评论

2009年9月20日 IT北瓜 64 条评论

      刚开始使用Quick Comments插件效果很好,这也是iNove主题作者mg12推荐的插件之一。但后来不知道怎么回事发现提交评论总是跳转到另一个页面,卸载重装该插件问题还是没有解决,有可能是装其他插件给弄成这样的。但不管到底是怎么回事,现在用不了总得小办法解决。既然插件不行,那么就试试看非插件方式吧。于是找到了Xiaorsz的这篇文章使用 jQuery 实现 wordpress 的 Ajax 留言,沿用了他的代码,做了一点细微的修改。总算恢复了ajax评论功能。

      具体代码:

      comments-ajax.php:

<?php
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('Our database has issues. Try again later.');
        } else {
            echo('We\'re currently having site problems. Try again later.');
        }
        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('The post you are trying to comment on does not currently exist in the database.');
} elseif ( 'closed' ==  $status->comment_status ) {
    do_action('comment_closed', $comment_post_ID);
    fail('Sorry, comments are closed for this item.');
} elseif ( in_array($status->post_status, array('draft', 'pending') ) ) {
    do_action('comment_on_draft', $comment_post_ID);
    fail('The post you are trying to comment on has not been published.');
}
$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('Sorry, you must be logged in to post a comment.');
}
$comment_type = '';
if ( get_option('require_name_email') && !$user->ID ) {
    if ( 6> strlen($comment_author_email) || '' == $comment_author )
        fail('Error: please fill the required fields (name, email).');
    elseif ( !is_email($comment_author_email))
        fail('Error: please enter a valid email address.');
}
if ( '' == $comment_content )
    fail('Error: please type a comment.');
// 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('Duplicate comment detected; it looks as though you\'ve already said that!');
}
$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;
?>
<li class="comment <?php if($comment->comment_author_email == get_the_author_email()) {echo 'admincomment';} else {echo 'regularcomment';} ?>" id="comment-<?php comment_ID() ?>">
		<div class="author">
			<div class="pic">
				<?php if (function_exists('get_avatar') && get_option('show_avatars')) { echo get_avatar($comment, 51); } ?>
			</div>
			<div class="name">
				<?php if (get_comment_author_url()) : ?>
					<a id="commentauthor-<?php comment_ID() ?>" class="url" href="<?php comment_author_url() ?>" rel="external nofollow">
				<?php else : ?>
					<span id="commentauthor-<?php comment_ID() ?>">
				<?php endif; ?>

				<?php comment_author(); ?>

				<?php if(get_comment_author_url()) : ?>
					</a>
				<?php else : ?>
					</span>
				<?php endif; ?>
			</div>
		</div>

		<div class="info">
			<div class="date">
				<?php printf( __('%1$s at %2$s', 'inove'), get_comment_time(__('F jS, Y', 'inove')), get_comment_time(__('H:i', 'inove')) ); ?>
					 | <a href="#comment-<?php comment_ID() ?>"><?php printf('#%1$s', ++$commentcount); ?></a>
			</div>
			<div class="act">
				<a href="javascript:void(0);" onclick="MGJS_CMT.reply('commentauthor-<?php comment_ID() ?>', 'comment-<?php comment_ID() ?>', 'comment');"><?php _e('Reply', 'inove'); ?></a> |
				<a href="javascript:void(0);" onclick="MGJS_CMT.quote('commentauthor-<?php comment_ID() ?>', 'comment-<?php comment_ID() ?>', 'commentbody-<?php comment_ID() ?>', 'comment');"><?php _e('Quote', 'inove'); ?></a>
				<?php
					if (function_exists("qc_comment_edit_link")) {
						qc_comment_edit_link('', ' | ', '', __('Edit', 'inove'));
					}
					edit_comment_link(__('Advanced edit', 'inove'), ' | ', '');
				?>
			</div>
			<div class="fixed"></div>
			<div class="content">
				<?php if ($comment->comment_approved == '0') : ?>
					<p><small><?php _e('Your comment is awaiting moderation.', 'inove'); ?></small></p>
				<?php endif; ?>

				<div id="commentbody-<?php comment_ID() ?>">
					<?php comment_text(); ?>
				</div>
			</div>
		</div>
		<div class="fixed"></div>

      comments.js:

$(document).ready(function() {
if ($('#commentform').length > 0) {
    $('#commentform').submit(function(){    //ID为 commentform 的表单提交时发生的函数,也就是整个留言输入框 form 的ID。
        jQuery.ajax({
            url: '/wp-content/themes/inove/comments-ajax.php',    //刚刚创建的 comments-ajax.php 文件的位置,建议用绝对路径。
            data: $('#commentform').serialize(),
            type: 'POST',
            beforeSend: function() {
            $('#commenterror').hide();
            var submit='<div id="commentload" style="display: none;;margin: 0 auto;text-align:center;"><img src="/wp-content/themes/inove/img/ajax-loader.gif" />评论提交中,请稍后...</div>';    //创建名为 submit 的字符串,稍后插入,这里的样式大家自己根据需要定义,那个背景图片自己去下哈。
	     var error='<div id="commenterror" style="display: none;margin: 0 auto;text-align:center;"></div>';    //创建名为 error 的字符串
	        $('#comments').after(submit);    // 在ID为 comments 的元素后插入刚定义的 submit
	        $('#comments').after(error);    // 同样插入刚定义的 error
                $('#commentload').slideDown();  // 让submit 向下滑出
            },
            error: function(request) {    //发生错误时
                $('#commentload').hide();    //隐藏  submit
                $('#commenterror').show("slow").html(request.responseText); //显示 error
            },
            success: function(data) {
                $('textarea').each(function(){
                    this.value='';
                });
                $('#commenterror').hide().html();
                if (!$('#thecomments').length) {
                $('#pinglist').before('<ol id="thecomments"></ol>');}
                $('#thecomments').append(data);    //向ID为 thecomments 的元素添加数据,也就是整个 ol 或 ul
				var new_comment = $('#thecomments li:last').hide();    //让最新添加的数据隐藏
				new_comment.slideDown(1000);    //再显示,这里是为了实现滑出的效果,不想要也可以直接显示
                $('#commentform:input').attr('disabled', true);
                $('#commentload').slideUp("slow");
		$('#nocomment').slideUp("slow");    //这是针对我模版而加的,因为我模版在没有留言时会有个 nocomment 的元素,我要让添加一条留言后他自动隐藏,要不然会矛盾,呵呵,这个可以自行选择要或不要
		setTimeout(function() {
                $('#commentform:input').removeAttr('disabled');
                }, 10000);        //这里是设置10秒之后才可以再次留言,自行设置,单位毫秒。
            }
        });
       return false;
   } );
}})

      不过还有一点小问题:

      1、刚提交的评论的序号总是#1,刷新页面后才能显示正常。

      2、管理员提交评论头像在左侧,在iNove主题中应该是在右侧才正确的,刷新页面后才能显示正常。根据Xiaorsz说可以将

<li class="comment <?php if($comment->comment_author_email == get_the_author_email()) {echo 'admincomment';} else {echo 'regularcomment';} ?>" id="comment-<?php comment_ID() ?>">

中的

get_the_author_email()

换成管理员的具体邮箱地址,不过我没有做测试,大家可以自己测试一下。

非插件方式添加评论表情

2009年9月15日 IT北瓜 没有评论

由于使用Auto HighSlide代替Highslide4WP,所以评论框下的表情符号也就没有了(停用了Highslide4WP)。虽然插入表情的插件有不少,但总觉得为了插入几个表情符号就去安装一个插件有点小题大做了。结果找到了Life Studio的Wordpress 非插件调用表情符,以下是我按照该文章所说的方法实现的具体效果:

红线框出来的部分就是刚才实现的效果啦。一直很喜欢QQ的表情,做得很逼真很Q!本来是要用QQ软件中的那套“圆脸”表情的,不过无意中在网上看到这套“方脸”的,觉得很有个性,就用上了。这套表情有22个,不过iNove主题中放22个就有一个表情换行了,所以我干脆就去掉了1个,只显示21个表情。