Kiểm tra bình luận trùng trên WordPress

Cập nhật lần cuối vào

WordPress có hàm kiểm tra nội dung bình luận trùng lặp khi người dùng gửi bình luận trên blog. Nếu bạn muốn dùng lại hàm này khi bạn viết code thêm bình luận trong giao diện hoặc plugin, bạn có thể viết lại để kiểm tra bình luận giống nhau trước khi thêm bình luận vào cơ sở dữ liệu.

Nội dung trùng lặp

Hàm bên dưới là mình trích lọc lại từ hàm wp_allow_comment, bạn chỉ cần lấy một phần nhỏ của hàm này chứ không cần dùng hết, bạn có thể dùng hàm bên dưới để kiểm tra bình luận trùng lặp.

function sb_check_duplicate_comment($commentdata) {
	if(!isset($commentdata['comment_post_ID']) || !isset($commentdata['comment_content']) || !isset($commentdata['comment_author'])) {
		return false;
	}
	if(!isset($commentdata['comment_parent'])) {
		$commentdata['comment_parent'] = 0;
	}
	global $wpdb;
	$dupe = $wpdb->prepare(
		"SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_parent = %s AND comment_approved != 'trash' AND ( comment_author = %s ",
		wp_unslash($commentdata['comment_post_ID']),
		wp_unslash($commentdata['comment_parent']),
		wp_unslash($commentdata['comment_author'])
	);
	if(isset($commentdata['comment_author_email'])) {
		$dupe .= $wpdb->prepare(
			"OR comment_author_email = %s ",
			wp_unslash($commentdata['comment_author_email'])
		);
	}
	$dupe .= $wpdb->prepare(
		") AND comment_content = %s LIMIT 1",
		wp_unslash($commentdata['comment_content'])
	);
	if($wpdb->get_var($dupe)) {
		return true;
	}
	return false;
}

Kết quả của hàm bên trên sẽ trả về giá trị kiểu Boolean. Khi bình luận là trùng lặp thì giá trị trả về là TRUE, ngược lại bình luận đó là duy nhất thì kết quả của hàm trả về sẽ có giá trị là FALSE. Bạn nên dùng hàm này để kiểm tra commentdata trước khi thêm bình luận vào cơ sở dữ liệu.