这个是在评论Ajax-1中的willin-kan版基础上改良的,也带再编辑模式。不过采用的是admin-ajax.php来处理ajax请求,将评论处理写入了functions.php
文件
首先是js
这段代码没有用on()方法来动态绑定 submit事件,所以在页面ajax重载时不会出现重复提交的现象,而且修改容器名已经被我集中到开头几个变量统一完成。看注释
$(document).ready(function() { ajaxComt(); }); function ajaxComt(){ var commentform = '#comment_form', // ××× form表单id comment = 'c_tarea', // ××× textarea 的id 不带# commentlist = 'comment-list', // ××× 评论列表ul或ol的class,不带点 respond = '#respond', // ××× 评论插入位置,插入在这个id之前 homeUrl = document.location.href.match(/http:\/\/([^\/]+)\//i)[0], // 主页地址,用于下面的提交函数 txt1 = '<div id="loading" class="text-info"> 正在提交, 请稍候...</div>', txt2 = '<div id="error">#</div>', txt3 = '"><div class="text-success"> OK !', edt1 = ' 刷新页面之前您可以<a rel="nofollow" class="comment-reply-link" href="#edit" onclick=\'return addComment.moveForm("', edt2 = ')\'>再次编辑评论</a></div>', cancel_edit = '取消编辑', edit, num = 1, $comments = $('#response'), // 评论数 $cancel = $('#cancel-comment-reply-link'), cancel_text = $cancel.text(), $submit = $(commentform+ '#submit'); $submit.attr('disabled', false), $body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body'), comm_array = []; comm_array.push(''); $('#'+comment).after(txt1 + txt2); // ××× textarea的id或class $('#loading').hide(); $('#error').hide(); // 评论提交 $(commentform).submit( //原版为动态绑定,即 $(document).on("submit", commentform, function() { if (edit) $('#'+comment).after('<input type="text" name="edit_id" id="edit_id" value="' + edit + '" style="display:none;" />'); $submit.attr('disabled', true).fadeTo('slow', 0.5); $('#loading').slideDown(); $.ajax({ url: homeUrl + '/wp-admin/admin-ajax.php', data: $(this).serialize() + "&action=ajax_comment", type: $(this).attr('method'), error: function(request) { $('#loading').slideUp(); $("#error").slideDown().html(request.responseText); setTimeout(function() { $submit.attr('disabled', false).fadeTo('slow', 1); $('#error').slideUp(); }, 3000); }, success: function(data) { $('#loading').hide(); comm_array.push($('#'+comment).val()); $('textarea').each(function() { this.value = '' }); var t = addComment, cancel = t.I('cancel-comment-reply-link'), temp = t.I('wp-temp-form-div'), respond = t.I(t.respondId), post = t.I('comment_post_ID').value, parent = t.I('comment_parent').value; // 增加评论数 if (!edit && $comments.length) { n = parseInt($comments.text().match(/\d+/)); // 匹配数字 $comments.text($comments.text().replace(n, n + 1)); } // 评论显示 new_htm = '" id="new_comm_' + num + '"></'; new_htm = (parent == '0') ? ('\n<ol style="clear:both;" class="'+commentlist+'" ' + new_htm + 'ol>') : ('\n<ul class="children' + new_htm + 'ul>'); ok_htm = '\n<div class="ajax-notice" id="success_' + num + txt3; div_ = (document.body.innerHTML.indexOf('div-comment-') == -1) ? '': ((document.body.innerHTML.indexOf('li-comment-') == -1) ? 'div-': ''); ok_htm = ok_htm.concat(edt1, div_, 'comment-', parent, '", "', parent, '", "respond", "', post, '", ', num, edt2); ok_htm += '</span><span></span>\n'; ok_htm += '</div>\n'; if($('#comments .comment-list').length>0){ // ××××××××××××××××××××非嵌套评论时,新评论显示插入的位置(按自己的喜好修改显示位置) $('#comments .comment-list').before(new_htm); } else{ $('#respond').after(new_htm); } $('#new_comm_' + num).append(data); $('#new_comm_' + num + ' li').append(ok_htm); $body.animate({scrollTop: $('#new_comm_' + num).offset().top - 200},900); countdown(); num++; edit = ''; $('*').remove('#edit_id'); cancel.style.display = 'none'; cancel.onclick = null; t.I('comment_parent').value = '0'; if (temp && respond) { temp.parentNode.insertBefore(respond, temp); temp.parentNode.removeChild(temp) } } }); return false; }); addComment = { moveForm: function(commId, parentId, respondId, postId, num) { var t = this, div, comm = t.I(commId), respond = t.I(respondId), cancel = t.I('cancel-comment-reply-link'), parent = t.I('comment_parent'), post = t.I('comment_post_ID'); if (edit) exit_prev_edit(); num ? (t.I(comment).value = comm_array[num], edit = t.I('new_comm_' + num).innerHTML.match(/(comment-)(\d+)/)[2], $new_sucs = $('#success_' + num), $new_sucs.hide(), $new_comm = $('#new_comm_' + num), $new_comm.hide(), $cancel.text(cancel_edit)) : $cancel.text(cancel_text); t.respondId = respondId; postId = postId || false; if (!t.I('wp-temp-form-div')) { div = document.createElement('div'); div.id = 'wp-temp-form-div'; div.style.display = 'none'; respond.parentNode.insertBefore(div, respond) } ! comm ? (temp = t.I('wp-temp-form-div'), t.I('comment_parent').value = '0', temp.parentNode.insertBefore(respond, temp), temp.parentNode.removeChild(temp)) : comm.parentNode.insertBefore(respond, comm.nextSibling); $body.animate({scrollTop: $('#respond').offset().top - 180},400); if (post && postId) post.value = postId; parent.value = parentId; cancel.style.display = ''; cancel.onclick = function() { if (edit) exit_prev_edit(); var t = addComment, temp = t.I('wp-temp-form-div'), respond = t.I(t.respondId); t.I('comment_parent').value = '0'; if (temp && respond) { temp.parentNode.insertBefore(respond, temp); temp.parentNode.removeChild(temp); } this.style.display = 'none'; this.onclick = null; return false; }; try { t.I(comment).focus(); } catch(e) {} return false; }, I: function(e) { return document.getElementById(e); } }; function exit_prev_edit() { $new_comm.show(); $new_sucs.show(); $('textarea').each(function() { this.value = '' }); edit = ''; } var wait = 15, submit_val = $submit.val(); function countdown() { if (wait > 0) { $submit.val(wait); wait--; setTimeout(countdown, 1000); } else { $submit.val(submit_val).attr('disabled', false).fadeTo('slow', 1); wait = 15; } } function grin(a) { var b; a = " " + a + " "; if (document.getElementById(comment) && document.getElementById(comment).type == "textarea") { b = document.getElementById(comment) } else { return false } if (document.selection) { b.focus(); sel = document.selection.createRange(); sel.text = a; b.focus() } else if (b.selectionStart || b.selectionStart == "0") { var c = b.selectionStart; var d = b.selectionEnd; var e = d; b.value = b.value.substring(0, c) + a + b.value.substring(d, b.value.length); e += a.length; b.focus(); b.selectionStart = e; b.selectionEnd = e } else { b.value += a; b.focus() } } }
加入functions.php的处理代码
可以单独写成一个php文件,然后在functions.php引用
<?php add_action('wp_ajax_nopriv_ajax_comment', 'ajax_comment_callback'); add_action('wp_ajax_ajax_comment', 'ajax_comment_callback'); function ajax_comment_callback(){ global $wpdb; $comment_post_ID = isset($_POST['comment_post_ID']) ? (int) $_POST['comment_post_ID'] : 0; $post = get_post($comment_post_ID); $post_author = $post->post_author; if ( empty($post->comment_status) ) { do_action('comment_id_not_found', $comment_post_ID); ajax_comment_err('Invalid comment status.'); } $status = get_post_status($post); $status_obj = get_post_status_object($status); if ( !comments_open($comment_post_ID) ) { do_action('comment_closed', $comment_post_ID); ajax_comment_err('Sorry, comments are closed for this item.'); } elseif ( 'trash' == $status ) { do_action('comment_on_trash', $comment_post_ID); ajax_comment_err('Invalid comment status.'); } elseif ( !$status_obj->public && !$status_obj->private ) { do_action('comment_on_draft', $comment_post_ID); ajax_comment_err('Invalid comment status.'); } elseif ( post_password_required($comment_post_ID) ) { do_action('comment_on_password_protected', $comment_post_ID); ajax_comment_err('Password Protected'); } else { do_action('pre_comment_on_post', $comment_post_ID); } $comment_author = ( isset($_POST['author']) ) ? trim(strip_tags($_POST['author'])) : null; $comment_author_email = ( isset($_POST['email']) ) ? trim($_POST['email']) : null; $comment_author_url = ( isset($_POST['url']) ) ? trim($_POST['url']) : null; $comment_content = ( isset($_POST['comment']) ) ? trim($_POST['comment']) : null; $user = wp_get_current_user(); if ( $user->exists() ) { if ( empty( $user->display_name ) ) $user->display_name=$user->user_login; $comment_author = esc_sql($user->display_name); $comment_author_email = esc_sql($user->user_email); $comment_author_url = esc_sql($user->user_url); $user_ID = esc_sql($user->ID); if ( current_user_can('unfiltered_html') ) { if ( wp_create_nonce('unfiltered-html-comment_' . $comment_post_ID) != $_POST['_wp_unfiltered_html_comment'] ) { kses_remove_filters(); kses_init_filters(); } } } else { if ( get_option('comment_registration') || 'private' == $status ) ajax_comment_err('Sorry, you must be logged in to post a comment.'); } $comment_type = ''; if ( get_option('require_name_email') && !$user->exists() ) { if ( 6 > strlen($comment_author_email) || '' == $comment_author ) ajax_comment_err( 'Error: please fill the required fields (name, email).' ); elseif ( !is_email($comment_author_email)) ajax_comment_err( 'Error: please enter a valid email address.' ); } if ( '' == $comment_content ) ajax_comment_err( 'Error: please type a comment.' ); $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) ) { ajax_comment_err('Duplicate comment detected; it looks as though you’ve already said that!'); } if ( $lasttime = $wpdb->get_var( $wpdb->prepare("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_author = %s ORDER BY comment_date DESC LIMIT 1", $comment_author) ) ) { $time_lastcomment = mysql2date('U', $lasttime, false); $time_newcomment = mysql2date('U', current_time('mysql', 1), false); $flood_die = apply_filters('comment_flood_filter', false, $time_lastcomment, $time_newcomment); if ( $flood_die ) { ajax_comment_err('You are posting comments too quickly. Slow down.'); } } $comment_parent = isset($_POST['comment_parent']) ? absint($_POST['comment_parent']) : 0; $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'comment_parent', 'user_ID'); $comment_id = wp_new_comment( $commentdata ); $comment = get_comment($comment_id); do_action('set_comment_cookies', $comment, $user); $comment_depth = 1; $tmp_c = $comment; while($tmp_c->comment_parent != 0){ $comment_depth++; $tmp_c = get_comment($tmp_c->comment_parent); } $GLOBALS['comment'] = $comment; ?> <?php //以下修改成你的评论结构,直接复制评论回调函数内的全部内容过来 $avatar = get_avatar ( $comment->comment_author_email, 55 ); echo '<li '; comment_class(); echo ' id="comment-'.get_comment_ID().'">'; //头像 echo '<div class="cl-avatar">'; echo $avatar; echo '</div>'; //评论主体 echo '<div class="cl-main" id="div-comment-'.get_comment_ID().'">'; //信息 echo '<div class="cl-meta">'; if ($comment->comment_type == '') { $author_link = empty ( $comment->comment_author_url ) ? null : ' href="' . $comment->comment_author_url . '"'; $author = $comment->comment_author; $comment_ID = get_comment_ID(); echo <<<EOF <span class="cl-author-{$comment_ID}"><a title="{$author}" rel="external nofollow" target="_blank" class="cl-author-url"{$author_link}>{$author}</a></span> EOF; } echo get_comment_time ( 'Y-n-j H:i' ); if ($comment->comment_approved !== '0'){ echo comment_reply_link( array_merge( $args, array('add_below' => 'div-comment', 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); echo edit_comment_link(__('( 编辑 )'),' - ',''); } echo '</div>'; //内容 echo '<div class="cl-content" >'; echo convert_smilies(get_comment_text()); if ($comment->comment_approved == '0'){ echo '<span class="cl-approved">(您的评论需要审核后才能显示!)</span><br />'; } echo '</div>'; echo '</div>'; // 回调函数结束 ?> <?php die(); } function ajax_comment_err($a) { header('HTTP/1.0 500 Internal Server Error'); header('Content-Type: text/plain;charset=UTF-8'); echo $a; exit; }
最后注意
提示函数变成了ajax_comment_err($a)
,所以某些包含wp_die()
的评论提示函数也要改一下,比如禁止英文、日文评论等函数的提示
这个版本不需要在意文件的相对路径。
本站文章除注明转载/出处外,均为本站原创或翻译。若要转载但请务必注明出处,尊重他人劳动成果。
转载请注明出处链接 : https://www.inlojv.com/4583.html