wordpress回复自动刷新ajax
时间 : 2023-12-09 17:33:02声明: : 文章内容来自网络,不保证准确性,请自行甄别信息有效性

最佳答案

要在WordPress中实现回复自动刷新,可以使用AJAX(Asynchronous JavaScript and XML)技术。AJAX允许在不刷新整个页面的情况下与服务器进行通信。

首先,在主题的functions.php文件中添加以下代码,以在前台加载并初始化AJAX:

```php

function add_ajax_script() {

wp_enqueue_script( 'my-ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );

wp_localize_script( 'my-ajax-script', 'myAjax', array( 'ajaxUrl' => admin_url( 'admin-ajax.php' ) ) );

}

add_action( 'wp_enqueue_scripts', 'add_ajax_script' );

该代码会加载并注册一个名为my-ajax-script的脚本,并将WordPress的AJAX请求URL传递给JavaScript脚本。

接下来,在主题的js文件夹下创建一个名为my-ajax-script.js的新文件,并将以下代码添加到该文件中:

```javascript

jQuery(document).ready(function($) {

$(".comment-form").submit(function(e) {

e.preventDefault();

var commentdata = $(this).serialize();

var postId = $(this).find(".comment_post_ID").val();

var parentId = $(this).find(".comment_parent").val();

$.ajax({

type: "POST",

url: myAjax.ajaxUrl,

data: commentdata + '&action=submit_comment&post=' + postId + '&parent=' + parentId,

success: function(response) {

// 在评论区域显示新的评论

$(".comments-wrapper").html(response);

// 清除评论表单

$(".comment-form").trigger("reset");

}

});

});

// 捕捉新评论的回复链接点击事件

$(".comments-wrapper").on("click", ".comment-reply-link", function(e) {

e.preventDefault();

var commentId = $(this).data("commentid");

var postId = $(this).data("postid");

$(".comment_parent").val(commentId);

$(".comment_post_ID").val(postId);

});

});

该JavaScript代码包括两部分。第一部分处理评论表单的提交事件,发送AJAX请求并在成功响应后刷新评论区域。第二部分处理回复链接的点击事件,将点击的评论ID和文章ID设置为隐藏字段的值,从而在回复评论时记录回复的上下文。

最后,在主题的comments.php文件中找到包含评论区域的HTML元素(例如`<div class="comments-wrapper">`),并将其类名添加到JavaScript代码的相应部分(例如`$(".comments-wrapper")`),以确保更新评论区域的正确元素。

通过执行以上步骤,便可以实现回复自动刷新功能。在用户提交评论时,将通过AJAX发送请求并在成功响应后,更新评论区域,无需整个页面刷新。

其他答案

在WordPress中实现回复自动刷新的功能可以通过Ajax来实现。首先,你需要在你的主题文件中添加以下的代码。

首先,你需要在主题的`functions.php`文件中添加以下代码来添加一个Ajax动作。

```php

add_action('wp_ajax_refresh_comments', 'refresh_comments');

add_action('wp_ajax_nopriv_refresh_comments', 'refresh_comments');

function refresh_comments() {

$post_id = $_POST['post_id'];

// 获取最新的评论

$comments = get_comments(array(

'post_id' => $post_id,

'status' => 'approve',

'order' => 'DESC',

'number' => '5' // 获取最近的5个评论

));

ob_start();

if ($comments) {

foreach ($comments as $comment) {

?>

<li>

<div class="comment-author"><?php echo $comment->comment_author; ?> 说:</div>

<div class="comment-content"><?php echo $comment->comment_content; ?></div>

</li>

<?php

}

} else {

echo '暂无评论';

}

$response = ob_get_clean();

echo $response;

die();

}

接下来,你需要在你的文章或页面模板中添加以下的HTML和JavaScript代码。

    get_the_ID(), 'status' => 'approve', 'order' => 'DESC', 'number' => '5' )); if ($comments) { foreach ($comments as $comment) { ?>
  • comment_author; ?> 说:
    comment_content; ?>

以上代码会在评论表单的提交后,使用Ajax请求后台刷新评论列表,然后将最新的评论显示出来。同时,也会清空评论输入框,方便用户输入下一条评论。

请注意,以上代码只是一个示例,你可能需要根据你的具体主题和需求进行修改。此外,你也可以根据需要自定义评论列表的样式和内容。