我正在構建一個 Wordpress 網站,我需要在其中顯示隨機帖子(通過 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 開發方面并不是那么出色,而且我找不到讓它作業的方法。
uj5u.com熱心網友回復:
對我來說最簡單的方法是添加 jQuery reload 功能。因此,在帶有按鈕的 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>)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/433818.html
標籤:php jQuery 阿贾克斯 WordPress while循环
