网上有流传很久的代码,但是有个很明显的缺点,那就是需要刷新!很多主题都使用Ajax 评论提交,也就是回复之后还需要刷新一下页面才可以,这还不如没有Ajax 评论提交。
昨晚睡觉的时候思考了一下大致思路:
首先判断内容可不可见,如果可见的话,那什么都不执行,如果不可见,则获取隐藏内容并更新内容。如果使用短代码的话则很难单独获取短代码的隐藏内容,这时候想到可以使用正则+hook的方式来操作内容,但是如果一篇文章里有多处隐藏内容的话操作起来就比较麻烦了。
所以最简单的方法就是直接获取文章内容然后DOM 操作更新文章内容,当然有更简单的方法,提交评论完用AJAX 请求下页面,然后刷新DOM,但这和刷新没啥区别。
方案有了,说下实现方法。
下面的代码加到functions.php
中,如果你的主题没有ajax 提交评论就只需要这部分代码就可以了,代码使用wp自带函数,旧方法是使用sql语句的。
function reply_to_read($atts, $content=null) { global $post; extract(shortcode_atts(array("notice" => '<p class="reply-to-read">温馨提示: 此处内容需要<a href="#respond" title="评论本文">评论本文</a>后才能查看.</p>'), $atts)); $email = null; $user_ID = (int) wp_get_current_user()->ID; if ($user_ID > 0) { $email = get_userdata($user_ID)->user_email; if ($email == get_the_author_meta( 'user_email' )) { return $content; } } else if (isset($_COOKIE['comment_author_email_' . COOKIEHASH])) { $email = str_replace('%40', '@', $_COOKIE['comment_author_email_' . COOKIEHASH]); } else { return $notice; } if (empty($email)) { return $notice; } $args = array( 'post_id' => get_the_ID(); ); $array_email = array(); $comments = get_comments($args); foreach($comments as $comment) { $comment_author_email = $comment->comment_author_email; array_push($array_email,$comment_author_email); } if (in_array($email,$array_email)) { return do_shortcode($content); } else { return $notice; } } add_shortcode('reply', 'reply_to_read');
如果你的主题支持ajax 评论提交,还需要把下面的代码加到functions.php
中
add_action('wp_ajax_nopriv_ajax_post_content', 'ajax_post_content'); add_action('wp_ajax_ajax_post_content', 'ajax_post_content'); function ajax_post_content(){ $args = array( 'p' => $_POST["id"] ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); the_content(); endwhile;endif; die; }
下面是js代码,需要jquery,entry-content
是文章内容的容器名,如果你的不是需要改成你自己的。
function get_post_content() { if ($(".reply-to-read").length > 0) { var ajax_data = { action: "ajax_post_content", id: $("#comment_post_ID").attr("value"), }; $.post("/wp-admin/admin-ajax.php", ajax_data, function(data) { $(".entry-content").html(data); }); } }
在你的ajax 评论提交成功后执行下get_post_content()
这个函数即可。
可能有朋友不知道在那调用,下面是最简单的ajax,只需要在请求成功后的回调函数sucesss里执行即可
$.ajax({ url: "test.html", context: document.body, success: function() { get_post_content(); } });
以上。