我正在为我管理的网站实现一个前端AJAX评论调节系统,但我很难让它正常工作。现在单击批准评论的链接会运行正确的php脚本,但会重新加载整个页面。所以它是可行的,但我希望在不重新加载整个页面的情况下使用ajax批准评论,但我缺乏javascript知识,这阻碍了我的工作。以下是代码(位于插件中):
add_filter( \'comment_text\', \'p3_comment_moderation_buttons\' );
function p3_comment_moderation_buttons ( ) {
if ( is_author() || current_user_can( \'moderate_comment\' ) ) {
// Adds moderation buttons under every comment
$comment_id = get_comment_ID();
$text = get_comment_text();
$nonce = wp_create_nonce( \'p3_comment_moderation\' );
$p3_approve_link = admin_url(\'admin-ajax.php?action=p3_comment_approve&comment_id=\'. $comment_id.\'&nonce=\'.$nonce);
$p3_edit_links = \'<div class="p3-edit-links"><a class="p3-comment-moderation" href="\' . $p3_approve_link . \'" data-comment_id="\' . $comment_id . \'" data-nonce="\' . $nonce . \'">Approve</a></div>\';
return $text . $p3_edit_links;
}
else{
return get_comment_text();
}
}
add_action("wp_ajax_p3_comment_approve", "p3_comment_approve");
function p3_comment_approve() {
if ( ! wp_verify_nonce( $_REQUEST[\'nonce\'], \'p3_comment_moderation\' ) ) {
exit("Go away!"); //If nonce check fails stop everything
}
$comment_id = $_REQUEST["comment_id"];
$success = wp_set_comment_status( $comment_id, \'approve\' );
$success = update_comment_meta( $comment_id, \'p3_comment_status\', \'\' );
if ( $success = true ) {
$result[\'type\'] = \'success\';
$result[\'comment_id\'] = $_REQUEST["comment_id"];
}
else {
$result[\'type\'] = \'error\';
$result[\'comment_id\'] = $_REQUEST["comment_id"];
echo "Something didn\'t work";
}
if(!empty($_SERVER[\'HTTP_X_REQUESTED_WITH\']) && strtolower($_SERVER[\'HTTP_X_REQUESTED_WITH\']) == \'xmlhttprequest\') {
$result = json_encode($result);
echo $result;
}
else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
die(); // this is required to return a proper result
}
add_action( \'init\', \'p3_comment_meta_script_enqueuer\' );
function p3_comment_meta_script_enqueuer() {
wp_register_script( "p3_comment_meta", plugins_url().\'/p3wp-comments/js/p3_comment_meta.js\', array(\'jquery\') );
wp_localize_script( "p3_comment_meta", \'p3cmetaAjax\', array( \'ajaxurl\' => admin_url( \'admin-ajax.php\' )));
wp_enqueue_script( \'jquery\' );
wp_enqueue_script( \'p3_comment_meta\' );
}
以及相应的javascript:jQuery(document).ready( function() {
jQuery(".p3-comment-moderation").click( function() {
comment_id = jQuery(this).attr("data-comment_id")
nonce = jQuery(this).attr("data-nonce")
jQuery.ajax({
type : "post",
dataType : "json",
url : p3cmetaAjax.ajaxurl,
data : {action: "p3_comment_meta", comment_id : comment_id, nonce: nonce},
success: function(response) {
if(response.type == "success") {
alert("Success!")
}
else {
alert("Something went wrong.")
}
}
})
})
})
有人能发现问题吗?顺便说一句,我已经修改了评论模板,以显示未批准的评论,以便可以在前端批准。我还计划将其扩展到使用自定义注释元,并扩展javascript,使其能够执行比显示恼人的警报更有用的操作
谢谢