在 Wordpress 中随机显示 post 并在不刷新页面的情况下更新内容

Show random post in Wordpress and update content without refreshing page

我正在构建一个 Wordpress 网站,我需要在其中显示随机 post(通过 WP_Query)并通过单击按钮重新加载其内容而不刷新整个页面。

这是我的HTML

<div id="randompost"></div>
<button type="button" id="reloadpost">Reload post</button>

这是我的 WP_Query

<?php

    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => 1,
        'orderby' => 'rand',
    );

    $arr_posts = new WP_Query( $args );
        if ( $arr_posts->have_posts() ) : while ( $arr_posts->have_posts() ) : $arr_posts->the_post(); ?>

                <h2><?php the_title();?></h2>
                <p><?php the_content();?></p>

    <?php endwhile; endif; ?>

我在网上阅读过有关 AJAX 的信息,但我不太擅长 JS 开发,而且我找不到让它工作的方法。

对我来说,最简单的方法是添加 jQuery 重新加载功能。因此,在 HTML 按钮下方,您将添加

<script>
$(document).on('click', '#reloadpost', function(){ 
    $("#randompost").load(location.href + " #randompost");
});
</script>

(您还必须使用 jQuery,因此如果您的页面上没有它,请添加 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>