feat(comments): AJAX fragment list/submit + load-more parity

Add REST comment/list + comment/submit HTML fragments, shared query
renderer for order/author/hottest, fix load-more policy and DOM
targets, and stop full-page scrapes for order/author/reload.
This commit is contained in:
kate522 committed 2026-07-12 08:59:50 +08:00
1 parent 0342aad9fb
commit 00d335ba16
8 files changed
+648 -222

No files matched your search

+14 -27
View File
@@ -268,41 +268,28 @@ class AKSRT_Admin {
wp_send_json_error(['message' => __('无效的文章 ID', 'aksrt')]);
}
$settings = class_exists('AKSRT_Settings') ? AKSRT_Settings::get_comment_display_settings() : [];
$per_page = max(1, (int) get_option('comments_per_page', 10));
$comment_query = new WP_Comment_Query([
'post_id' => $post_id,
'status' => 'approve',
'number' => $per_page,
'offset' => ($page - 1) * $per_page,
'orderby' => 'comment_date_gmt',
'order' => !empty($settings['order']) && strtoupper((string) $settings['order']) === 'ASC' ? 'ASC' : 'DESC',
]);
$comments = $comment_query->comments;
$order = sanitize_key((string) ($_POST['comment_order'] ?? $_POST['order'] ?? 'newest'));
$author_only = !empty($_POST['author_only']) || (isset($_POST['aksrt_author_only']) && (int) $_POST['aksrt_author_only'] === 1);
ob_start();
if (!empty($comments) && function_exists('aksrt_comment_callback')) {
set_query_var('aksrt_comment_settings', $settings);
wp_list_comments([
'callback' => 'aksrt_comment_callback',
'style' => 'ul',
'avatar_size' => max(24, (int) ($settings['avatar_size'] ?? 48)),
'max_depth' => max(1, (int) ($settings['nested_depth'] ?? 3)),
], $comments);
if (!function_exists('aksrt_comments_query_for_post') || !function_exists('aksrt_comments_render_items_html')) {
wp_send_json_error(['message' => __('评论加载不可用', 'aksrt')]);
}
$html = ob_get_clean();
$total = get_comments([
'post_id' => $post_id,
'status' => 'approve',
'count' => true,
$result = aksrt_comments_query_for_post($post_id, [
'page' => $page,
'order' => $order,
'author_only' => $author_only,
]);
$max_pages = (int) ceil(((int) $total) / $per_page);
$html = aksrt_comments_render_items_html($result['comments'], $result['settings'], $result['order']);
wp_send_json_success([
'html' => $html,
'has_more' => $page < $max_pages,
'has_more' => $page < (int) $result['max_pages'],
'page' => $page,
'order' => $result['order'],
'total' => (int) $result['total'],
'max_pages'=> (int) $result['max_pages'],
]);
}
}
+189 -1
View File
@@ -27,6 +27,24 @@ class AKSRT_Comment_Actions {
}
public function register_routes(): void {
register_rest_route('aksrt/v1', '/comment/list', [
'methods' => \WP_REST_Server::READABLE,
'callback' => [$this, 'list_comments'],
'permission_callback' => '__return_true',
'args' => [
'post_id' => ['required' => true, 'type' => 'integer', 'sanitize_callback' => 'absint'],
'page' => ['required' => false, 'type' => 'integer', 'default' => 1, 'sanitize_callback' => 'absint'],
'order' => ['required' => false, 'type' => 'string', 'default' => 'newest', 'sanitize_callback' => 'sanitize_key'],
'author_only' => ['required' => false, 'type' => 'boolean', 'default' => false],
],
]);
register_rest_route('aksrt/v1', '/comment/submit', [
'methods' => 'POST',
'callback' => [$this, 'submit_comment'],
'permission_callback' => '__return_true',
]);
register_rest_route('aksrt/v1', '/comment/edit', [
'methods' => 'POST',
'callback' => [$this, 'edit_comment'],
@@ -127,6 +145,172 @@ class AKSRT_Comment_Actions {
return $this->permissions((int) $request->get_param('comment_id'))['can_pin'];
}
/**
* Fragment list for order / author / page without full HTML scrape.
*/
public function list_comments(\WP_REST_Request $request): \WP_REST_Response {
$post_id = (int) $request->get_param('post_id');
$post = get_post($post_id);
if (!$post) {
return new \WP_REST_Response([
'success' => false,
'code' => 'post_not_found',
'message' => __('文章不存在。', 'aksrt'),
], 404);
}
if (!function_exists('aksrt_comments_render_list_fragment')) {
return new \WP_REST_Response([
'success' => false,
'code' => 'fragment_unavailable',
'message' => __('评论片段渲染不可用。', 'aksrt'),
], 500);
}
$order = sanitize_key((string) ($request->get_param('order') ?: 'newest'));
$author_only = (bool) $request->get_param('author_only');
$page = max(1, (int) ($request->get_param('page') ?: 1));
$fragment = aksrt_comments_render_list_fragment($post_id, [
'order' => $order,
'author_only' => $author_only,
'page' => $page,
]);
return new \WP_REST_Response([
'success' => true,
'data' => $fragment,
]);
}
/**
* AJAX submit with HTML item for local insert.
* Runs through native WP comment pipeline (preprocess_comment / moderation).
*/
public function submit_comment(\WP_REST_Request $request): \WP_REST_Response {
$params = $request->get_json_params();
if (!is_array($params) || empty($params)) {
$params = $request->get_params();
}
if (!is_array($params)) {
$params = [];
}
$post_id = absint($params['comment_post_ID'] ?? $params['post_id'] ?? 0);
$content = isset($params['comment']) ? (string) $params['comment'] : '';
$parent = absint($params['comment_parent'] ?? 0);
if ($post_id <= 0 || trim(wp_strip_all_tags($content)) === '') {
return new \WP_REST_Response([
'success' => false,
'code' => 'invalid_payload',
'message' => __('请输入评论内容。', 'aksrt'),
], 400);
}
$post = get_post($post_id);
if (!$post || !comments_open($post_id)) {
return new \WP_REST_Response([
'success' => false,
'code' => 'comments_closed',
'message' => __('评论已关闭。', 'aksrt'),
], 403);
}
$nonce = (string) ($params['_aksrt_comment_nonce'] ?? $params['_wpnonce'] ?? '');
if ($nonce !== '' && !wp_verify_nonce($nonce, 'aksrt_comment_nonce') && !wp_verify_nonce($nonce, 'wp_rest')) {
return new \WP_REST_Response([
'success' => false,
'code' => 'invalid_nonce',
'message' => __('安全校验失败,请刷新后重试。', 'aksrt'),
], 403);
}
$user = wp_get_current_user();
$commentdata = [
'comment_post_ID' => $post_id,
'comment_content' => $content,
'comment_parent' => $parent,
'comment_type' => '',
'comment_author_IP' => isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash((string) $_SERVER['REMOTE_ADDR'])) : '',
'comment_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash((string) $_SERVER['HTTP_USER_AGENT'])) : '',
'comment_date' => current_time('mysql'),
'comment_date_gmt' => current_time('mysql', true),
];
if ($user && $user->ID > 0) {
$commentdata['user_id'] = (int) $user->ID;
$commentdata['comment_author'] = $user->display_name ?: $user->user_login;
$commentdata['comment_author_email'] = $user->user_email;
$commentdata['comment_author_url'] = $user->user_url;
} else {
$commentdata['user_id'] = 0;
$commentdata['comment_author'] = sanitize_text_field((string) ($params['author'] ?? ''));
$commentdata['comment_author_email'] = sanitize_email((string) ($params['email'] ?? ''));
$commentdata['comment_author_url'] = esc_url_raw((string) ($params['url'] ?? ''));
if ($commentdata['comment_author'] === '' || $commentdata['comment_author_email'] === '') {
return new \WP_REST_Response([
'success' => false,
'code' => 'guest_fields_required',
'message' => __('请填写昵称和邮箱。', 'aksrt'),
], 400);
}
}
foreach (['author', 'email', 'url', 'comment', 'comment_post_ID', 'comment_parent', '_aksrt_comment_nonce'] as $k) {
if (isset($params[$k])) {
$_POST[$k] = $params[$k];
}
}
foreach ($params as $k => $v) {
if (is_string($k) && (str_contains($k, 'captcha') || str_starts_with($k, 'g-recaptcha') || str_starts_with($k, 'cf-turnstile') || str_starts_with($k, 'h-captcha'))) {
$_POST[$k] = $v;
}
}
$comment_id = wp_new_comment(wp_slash($commentdata), true);
if (is_wp_error($comment_id)) {
return new \WP_REST_Response([
'success' => false,
'code' => $comment_id->get_error_code() ?: 'submit_failed',
'message' => $comment_id->get_error_message() ?: __('评论提交失败。', 'aksrt'),
], 400);
}
$comment = get_comment((int) $comment_id);
if (!$comment) {
return new \WP_REST_Response([
'success' => false,
'code' => 'submit_failed',
'message' => __('评论提交失败。', 'aksrt'),
], 500);
}
$settings = class_exists('AKSRT_Settings') ? AKSRT_Settings::get_comment_display_settings() : [];
$html = function_exists('aksrt_comments_render_single_html')
? aksrt_comments_render_single_html($comment, $settings)
: '';
$needs_moderation = '0' === (string) $comment->comment_approved;
$wait_time = 0;
return new \WP_REST_Response([
'success' => true,
'code' => 'submitted',
'message' => $needs_moderation ? __('评论已提交,等待管理员审核', 'aksrt') : __('评论发布成功', 'aksrt'),
'html' => $html,
'is_reply'=> $parent > 0,
'parent_id' => $parent,
'needs_moderation' => $needs_moderation,
'wait_time' => $wait_time,
'data' => [
'comment_id' => (int) $comment_id,
'approved' => (string) $comment->comment_approved,
],
]);
}
/**
* Edit comment content
*/
@@ -168,12 +352,16 @@ class AKSRT_Comment_Actions {
], 500);
}
$rendered = function_exists('aksrt_render_comment_content')
? aksrt_render_comment_content($clean_content)
: wpautop($clean_content);
return new \WP_REST_Response([
'success' => true,
'code' => 'updated',
'message' => __('评论已更新。', 'aksrt'),
'data' => [
'content' => $clean_content,
'content' => $rendered,
],
]);
}
+253
View File
@@ -142,6 +142,259 @@ if (!function_exists('aksrt_comments_apply_hottest_order')) :
}
endif;
if (!function_exists('aksrt_comments_normalize_order')) :
/**
* Normalize comment order key.
*/
function aksrt_comments_normalize_order(string $order = ''): string {
$order = sanitize_key($order);
if (!in_array($order, ['newest', 'oldest', 'hottest'], true)) {
$settings = class_exists('AKSRT_Settings')
? AKSRT_Settings::get_comment_display_settings()
: [];
$order = (($settings['order'] ?? 'desc') === 'asc') ? 'oldest' : 'newest';
}
if (!in_array($order, ['newest', 'oldest', 'hottest'], true)) {
$order = 'newest';
}
return $order;
}
endif;
if (!function_exists('aksrt_comments_query_for_post')) :
/**
* Shared comment query for first paint / fragment / load-more.
*
* @return array{comments:array<int,\WP_Comment>,total:int,max_pages:int,page:int,order:string,author_only:bool,settings:array}
*/
function aksrt_comments_query_for_post(int $post_id, array $args = []): array {
$settings = class_exists('AKSRT_Settings')
? AKSRT_Settings::get_comment_display_settings()
: [];
$order = aksrt_comments_normalize_order((string) ($args['order'] ?? ''));
$author_only = !empty($args['author_only']);
$page = max(1, (int) ($args['page'] ?? 1));
$per_page = max(1, (int) ($args['per_page'] ?? get_option('comments_per_page', 10)));
$include_unapproved_for_user = (int) ($args['include_unapproved_user'] ?? 0);
$query_args = [
'post_id' => $post_id,
'status' => 'approve',
'number' => $per_page,
'offset' => ($page - 1) * $per_page,
'orderby' => 'comment_date_gmt',
'order' => $order === 'oldest' ? 'ASC' : 'DESC',
'hierarchical' => 'threaded',
];
if ($author_only) {
$author_id = (int) get_post_field('post_author', $post_id);
if ($author_id > 0) {
$query_args['user_id'] = $author_id;
$query_args['hierarchical'] = false;
}
}
if ($include_unapproved_for_user > 0) {
// WP_Comment_Query does not support mixed status easily; keep approve only for list fragment.
}
// Hottest uses meta_value_num when meta exists; fall back to date.
$hottest_filter = null;
if ($order === 'hottest') {
$query_args['orderby'] = 'meta_value_num';
$query_args['meta_key'] = 'aksrt_comment_likes';
$query_args['order'] = 'DESC';
// Ensure comments without like meta still appear.
$query_args['meta_query'] = [
'relation' => 'OR',
[
'key' => 'aksrt_comment_likes',
'compare' => 'EXISTS',
],
[
'key' => 'aksrt_comment_likes',
'compare' => 'NOT EXISTS',
],
];
// Prefer clauses filter for stable hottest ordering.
$hottest_filter = static function ($clauses) {
global $wpdb;
if (strpos($clauses['join'], 'aksrt_cm_hot') === false) {
$clauses['join'] .= " LEFT JOIN {$wpdb->commentmeta} AS aksrt_cm_hot ON ({$wpdb->comments}.comment_ID = aksrt_cm_hot.comment_id AND aksrt_cm_hot.meta_key = 'aksrt_comment_likes')";
}
$clauses['orderby'] = 'CAST(COALESCE(aksrt_cm_hot.meta_value, 0) AS UNSIGNED) DESC, ' . $wpdb->comments . '.comment_date_gmt DESC';
return $clauses;
};
add_filter('comments_clauses', $hottest_filter, 20);
// Prefer date orderby with clauses override.
$query_args['orderby'] = 'comment_date_gmt';
unset($query_args['meta_key'], $query_args['meta_query']);
}
$comment_query = new WP_Comment_Query($query_args);
$comments = is_array($comment_query->comments) ? $comment_query->comments : [];
if ($hottest_filter) {
remove_filter('comments_clauses', $hottest_filter, 20);
}
// Pin reorder for page 1 when not author-only.
if ($page === 1 && !$author_only && function_exists('aksrt_reorder_pinned_comments')) {
$comments = aksrt_reorder_pinned_comments($comments, $post_id);
}
$count_args = [
'post_id' => $post_id,
'status' => 'approve',
'count' => true,
];
if ($author_only) {
$author_id = (int) get_post_field('post_author', $post_id);
if ($author_id > 0) {
$count_args['user_id'] = $author_id;
}
}
$total = (int) get_comments($count_args);
$max_pages = (int) max(1, (int) ceil($total / $per_page));
return [
'comments' => $comments,
'total' => $total,
'max_pages' => $max_pages,
'page' => $page,
'order' => $order,
'author_only' => $author_only,
'settings' => $settings,
'per_page' => $per_page,
];
}
endif;
if (!function_exists('aksrt_comments_render_items_html')) :
/**
* Render comment list items HTML via canonical callback.
*
* @param array<int,\WP_Comment> $comments
* @param array<string,mixed> $settings
* @param string $order
*/
function aksrt_comments_render_items_html(array $comments, array $settings = [], string $order = 'newest'): string {
if (empty($comments) || !function_exists('aksrt_comment_callback')) {
return '';
}
set_query_var('aksrt_comment_settings', $settings);
set_query_var('aksrt_comment_order', aksrt_comments_normalize_order($order));
$avatar = max(24, (int) ($settings['avatar_size'] ?? 48));
$depth = max(1, (int) ($settings['nested_depth'] ?? 3));
$reverse = $order === 'newest';
ob_start();
wp_list_comments([
'callback' => 'aksrt_comment_callback',
'style' => 'ol',
'avatar_size' => $avatar,
'max_depth' => $depth,
'reverse_top_level' => $reverse,
'reverse_children' => $reverse,
], $comments);
return (string) ob_get_clean();
}
endif;
if (!function_exists('aksrt_comments_render_single_html')) :
/**
* Render one comment item HTML.
*/
function aksrt_comments_render_single_html(\WP_Comment $comment, array $settings = []): string {
$html = aksrt_comments_render_items_html([$comment], $settings, 'newest');
return $html;
}
endif;
if (!function_exists('aksrt_comments_render_list_fragment')) :
/**
* Fragment payload for order/author/page AJAX.
*
* @return array{html:string,filter_html:string,pagination_html:string,count_text:string,total:int,max_pages:int,page:int,order:string,author_only:bool,empty:bool}
*/
function aksrt_comments_render_list_fragment(int $post_id, array $args = []): array {
$result = aksrt_comments_query_for_post($post_id, $args);
$settings = $result['settings'];
$order = $result['order'];
$author_only = !empty($result['author_only']);
$page = (int) $result['page'];
$max_pages = (int) $result['max_pages'];
$total = (int) $result['total'];
// Fake globals needed by pagination helpers when not on singular loop.
$GLOBALS['post'] = get_post($post_id);
setup_postdata($GLOBALS['post']);
set_query_var('cpage', $page);
set_query_var('aksrt_comment_order', $order);
set_query_var('aksrt_comment_settings', $settings);
$items_html = aksrt_comments_render_items_html($result['comments'], $settings, $order);
$ctx = [
'order' => $order,
'author_only' => $author_only,
'post_author_id' => (int) get_post_field('post_author', $post_id),
'corderby_enabled' => !empty($settings['corderby']),
'comment_count' => $total,
'empty_text' => (string) ($settings['empty_text'] ?? __('暂无评论,来做第一个评论的人吧~', 'aksrt')),
];
ob_start();
if (function_exists('aksrt_comments_render_filter') && !empty($ctx['corderby_enabled'])) {
aksrt_comments_render_filter($ctx);
}
$filter_html = (string) ob_get_clean();
ob_start();
if ($items_html === '' && function_exists('aksrt_comments_render_empty')) {
aksrt_comments_render_empty($ctx);
} else {
echo '<div id="postcomments"><ol class="commentlist list-unstyled" id="comment-list">';
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- rendered comment markup.
echo $items_html;
echo '</ol></div>';
}
$list_html = (string) ob_get_clean();
ob_start();
if (function_exists('aksrt_render_comment_pagination') && $max_pages > 1) {
// Temporarily override page counts via filter.
$pages_filter = static function () use ($max_pages) {
return $max_pages;
};
add_filter('get_comment_pages_count', $pages_filter);
aksrt_render_comment_pagination();
remove_filter('get_comment_pages_count', $pages_filter);
}
$pagination_html = (string) ob_get_clean();
wp_reset_postdata();
return [
'html' => $list_html,
'items_html' => $items_html,
'filter_html' => $filter_html,
'pagination_html' => $pagination_html,
'count_text' => sprintf(__('共 %d 条', 'aksrt'), $total),
'total' => $total,
'max_pages' => $max_pages,
'page' => $page,
'order' => $order,
'author_only' => $author_only,
'empty' => $items_html === '',
];
}
endif;
if (!function_exists('aksrt_comments_render_signarea')) :
/**
* Login-required gate.
+4 -4
View File
@@ -1063,7 +1063,7 @@ if (!function_exists('aksrt_comment_callback')) :
<li <?php comment_class('aksrt-comment ' . $li_classes); ?> id="comment-<?php echo esc_attr((string) $comment_id); ?>" data-comment-id="<?php echo esc_attr((string) $comment_id); ?>" data-comment-status="<?php echo esc_attr((string) $comment->comment_approved); ?>">
<ul class="list-inline">
<li class="comt-main" id="div-comment-<?php echo esc_attr((string) $comment_id); ?>">
<div class="comment-header">
<div class="comment-header aksrt-comment__header">
<div class="author-box">
<?php echo get_avatar($comment, $avatar_size, '', '', ['class' => 'avatar-img comt-avatar']); ?>
<span class="aksrt-comment__author"><?php comment_author_link(); ?></span>
@@ -1074,16 +1074,16 @@ if (!function_exists('aksrt_comment_callback')) :
<span class="aksrt-comment__badge aksrt-comment__badge--pinned"><i class="fas fa-thumbtack" aria-hidden="true"></i> <?php esc_html_e('置顶', 'aksrt'); ?></span>
<?php endif; ?>
</div>
<time class="post-time" datetime="<?php echo esc_attr($comment_date); ?>"><?php echo esc_html($comment_label); ?></time>
<time class="post-time aksrt-comment__time" datetime="<?php echo esc_attr($comment_date); ?>"><?php echo esc_html($comment_label); ?></time>
</div>
<div class="comment-content" id="comment-content-<?php echo esc_attr((string) $comment_id); ?>">
<div class="comment-content aksrt-comment__text" id="comment-content-<?php echo esc_attr((string) $comment_id); ?>">
<?php if ($is_pending) : ?>
<p class="awaiting-moderation"><?php esc_html_e('您的评论正在等待审核。', 'aksrt'); ?></p>
<?php else : ?>
<?php echo aksrt_render_comment_content((string) get_comment_text($comment)); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
<?php endif; ?>
</div>
<div class="comment-footer comt-meta">
<div class="comment-footer comt-meta aksrt-comment__actions">
<?php if ($like_enabled) : ?>
<button type="button" class="aksrt-comment__like<?php echo $is_liked ? ' is-active' : ''; ?>" data-comment-action="like" data-active="<?php echo $is_liked ? '1' : '0'; ?>" aria-pressed="<?php echo $is_liked ? 'true' : 'false'; ?>">
<i class="<?php echo $is_liked ? 'fas' : 'far'; ?> fa-thumbs-up" aria-hidden="true"></i>
+4 -2
View File
@@ -1347,9 +1347,10 @@ if (!function_exists('aksrt_render_comment_pagination')) {
$max_pages = $per_page > 0 ? ceil($total / $per_page) : 1;
$current_page = max(1, get_query_var('cpage', 1));
$comment_order = (string) get_query_var('aksrt_comment_order', 'newest');
if (!in_array($comment_order, ['newest', 'oldest'], true)) {
if (!in_array($comment_order, ['newest', 'oldest', 'hottest'], true)) {
$comment_order = 'newest';
}
$author_only = isset($_GET['aksrt_author_only']) && (int) $_GET['aksrt_author_only'] === 1;
if ($current_page >= $max_pages || $total <= $per_page) {
return;
@@ -1361,7 +1362,8 @@ if (!function_exists('aksrt_render_comment_pagination')) {
data-next-page="<?php echo esc_attr((string) ($current_page + 1)); ?>"
data-max-pages="<?php echo esc_attr((string) ((int) $max_pages)); ?>"
data-post-id="<?php echo esc_attr((string) $post_id); ?>"
data-comment-order="<?php echo esc_attr($comment_order); ?>">
data-comment-order="<?php echo esc_attr($comment_order); ?>"
data-author-only="<?php echo $author_only ? '1' : '0'; ?>">
<?php if ($comment_pagination_mode === 'load_more') : ?>
<button type="button" class="aksrt-load-more-btn aksrt-load-more-btn--comment">
<span class="aksrt-load-more-btn__text"><?php esc_html_e('加载更多评论', 'aksrt'); ?></span>