Phương thức xử lí
Đầu tiên, để lấy bình luận ở nhiều bài viết, bạn thêm phương thức sau vào functions.php.
/**
* Lấy bình luận từ nhiều bài viết một cách an toàn và hiệu quả
*/
function get_posts_comments(array $post_ids, int $per = 10, int $page = 1) {
global $wpdb;
// Xử lý mảng ID để đảm bảo an toàn
$post_ids = array_filter(array_map('intval', $post_ids));
if (empty($post_ids)) return [];
$offset = max(0, ($page - 1) * $per);
$placeholders = implode(',', array_fill(0, count($post_ids), '%d'));
$sql = $wpdb->prepare(
"SELECT comment_ID, comment_parent, comment_date, comment_content, comment_post_ID, comment_author, user_id
FROM {$wpdb->comments}
WHERE comment_post_ID IN ($placeholders) AND comment_approved = 1
ORDER BY comment_date DESC
LIMIT %d OFFSET %d",
[...$post_ids, $per, $offset]
);
return $wpdb->get_results($sql);
}
Sử dụng
Để sử dụng, bạn cần truyền vào một mảng là ID của các bài viết cần lấy bình luận, ví dụ.
$post_ids = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$per = 10;
$page = 1;
$comments = get_posts_comments($post_ids, $per, $page);
Chúc các bạn thành công!
Bình luận