为WordPress主题添加AJAX无刷新提交评论功能

我这主题在提交评论后会刷新整个网页,别人家的都不是这样子的,太落后了。必须要改。

1、在function.php文件加入以下代码

<?php
define('AC_VERSION','2.0.0');

if ( version_compare( $GLOBALS['wp_version'], '4.4-alpha', '<' ) ) {
	wp_die('请升级到4.4以上版本');
}

if(!function_exists('fa_ajax_comment_scripts')) :

    function fa_ajax_comment_scripts(){
        if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
            wp_enqueue_script( 'comment-reply' );
        }
        wp_enqueue_style( 'ajax-comment', get_template_directory_uri() . '/ajax-comment/app.css', array(), AC_VERSION );
        wp_enqueue_script( 'ajax-comment', get_template_directory_uri() . '/ajax-comment/app.js', array( 'jquery' ), AC_VERSION , true );
        wp_localize_script( 'ajax-comment', 'ajaxcomment', array(
            'ajax_url'   => admin_url('admin-ajax.php'),
            'order' => get_option('comment_order'),
            'formpostion' => 'bottom', //默认为bottom,如果你的表单在顶部则设置为top。
        ) );
    }

endif;

if(!function_exists('fa_ajax_comment_err')) :

    function fa_ajax_comment_err($a) {
        header('HTTP/1.0 500 Internal Server Error');
        header('Content-Type: text/plain;charset=UTF-8');
        echo $a;
        exit;
    }

endif;

if(!function_exists('fa_ajax_comment_callback')) :

    function fa_ajax_comment_callback(){
        $comment = wp_handle_comment_submission( wp_unslash( $_POST ) );
        if ( is_wp_error( $comment ) ) {
            $data = $comment->get_error_data();
            if ( ! empty( $data ) ) {
            	fa_ajax_comment_err($comment->get_error_message());
            } else {
                exit;
            }
        }
        $user = wp_get_current_user();
        do_action('set_comment_cookies', $comment, $user);
        $GLOBALS['comment'] = $comment; //根据你的评论结构自行修改,如使用默认主题则无需修改
        ?>
        <li <?php comment_class(); ?>>
            <article class="comment-body">
                <footer class="comment-meta">
                    <div class="comment-author vcard">
                        <?php echo get_avatar( $comment, $size = '56')?>
                        <b class="fn">
                            <?php echo get_comment_author_link();?>
                        </b>
                    </div>
                    <div class="comment-metadata">
                        <?php echo get_comment_date(); ?>
                    </div>
                </footer>
                <div class="comment-content">
                    <?php comment_text(); ?>
                </div>
            </article>
        </li>
        <?php die();
    }

endif;

add_action( 'wp_enqueue_scripts', 'fa_ajax_comment_scripts' );
add_action('wp_ajax_nopriv_ajax_comment', 'fa_ajax_comment_callback');
add_action('wp_ajax_ajax_comment', 'fa_ajax_comment_callback');

2、新建 app.js ,加入以下代码

jQuery(document).ready(function(jQuery) {
    var __cancel = jQuery('#cancel-comment-reply-link'),
        __cancel_text = __cancel.text(),
        __list = 'comment-list';//your comment wrapprer
    jQuery(document).on("submit", "#commentform", function() {
        jQuery.ajax({
            url: ajaxcomment.ajax_url,
            data: jQuery(this).serialize() + "&action=ajax_comment",
            type: jQuery(this).attr('method'),
            beforeSend: faAjax.createButterbar("提交中...."),
            error: function(request) {
                var t = faAjax;
                t.createButterbar(request.responseText);
            },
            success: function(data) {
                jQuery('textarea').each(function() {
                    this.value = ''
                });
                var t = faAjax,
                    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 (parent != '0') {
                    jQuery('#respond').before('<ol class="children">' + data + '</ol>');
                } else if (!jQuery('.' + __list ).length) {
                    if (ajaxcomment.formpostion == 'bottom') {
                        jQuery('#respond').before('<ol class="' + __list + '">' + data + '</ol>');
                    } else {
                        jQuery('#respond').after('<ol class="' + __list + '">' + data + '</ol>');
                    }

                } else {
                    if (ajaxcomment.order == 'asc') {
                        jQuery('.' + __list ).append(data); // your comments wrapper
                    } else {
                        jQuery('.' + __list ).prepend(data); // your comments wrapper
                    }
                }
                t.createButterbar("提交成功");
                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;
    });
    faAjax = {
        I: function(e) {
            return document.getElementById(e);
        },
        clearButterbar: function(e) {
            if (jQuery(".butterBar").length > 0) {
                jQuery(".butterBar").remove();
            }
        },
        createButterbar: function(message) {
            var t = this;
            t.clearButterbar();
            jQuery("body").append('<div class="butterBar butterBar--center"><p class="butterBar-message">' + message + '</p></div>');
            setTimeout("jQuery('.butterBar').remove()", 3000);
        }
    };
});

3、新建 app.css ,加入以下代码

.butterBar{
    margin-left:36%;
    max-width:640px;
    position:fixed;
    text-align:center;
    top:0;
    width:58%;
    z-index:800
}
.butterBar--center{
    left:50%;
    margin-left:-320px
}
.butterBar-message{
    background:rgba(255,255,255,0.97);
    border-bottom-left-radius:4px;
    border-bottom-right-radius:4px;
    box-shadow:0 1px 1px rgba(0,0,0,0.25),0 0 1px rgba(0,0,0,0.35);
    display:inline-block;
    font-size:14px;
    margin-bottom:0;
    padding:12px 25px
}

4、新建文件夹ajax-comment,将app.js和app.css放入其中。将文件夹ajax-comment放在主题根目录。
其中布局需要根据自身主题进行微调。

效果见本站。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

  1. 北忘山 北忘山 说道:

    我就来试试

  2. 安七七 说道:

    呐,试试看

  3. 5464 5464 说道:

    能行吗 :021:

  4. 默默 说道:

    这个可以的

  5. 仔仔 仔仔 说道:

    试试看

  6. 测试 测试 说道:

    吧吧吧v

  7. 成全 说道:

    啥效果

    1. 5464 5464 说道:

      测试看看 :029:

  8. 陈大萨 陈大萨 说道:

    :001: 我看看效果

  9. 23un 说道:

    看看你的这个评论效果

  10. BLUESUNSHINE BLUESUNSHINE 说道:

    看看无刷新评论提交效果

  11. ko哥 说道:

    看一下没刷新提交评论是啥样子的