您可以为ajax请求创建一个函数,并设置超时以使其重复。您还需要发送当前正在显示的新闻文章的ID,以便从PHP中的新WP\\U查询中排除它们
更新-现在使用数据属性创建post ID数组,以排除下一个ajax请求。
居住php
<div class="latest-news">
<?php
$current_posts_ids = array();
$args = array(
\'post_type\' => \'post\',
\'post_status\' => \'publish\',
);
$my_posts = new WP_Query( $args );
if ( $my_posts->have_posts() ) : ?>
<div class="posts">
<?php while ( $my_posts->have_posts() ) : $my_posts->the_post() ?>
<?php array_push($current_posts_ids, get_the_ID() );?>
<article data-id="<?php echo get_the_ID()?>">
<h2><?php the_title() ?></h2>
<p><?php the_excerpt() ?><p>
</article>
<?php endwhile ?>
</div>
<?php endif ?>
</div>
<script>
$(document).ready(function(){
var ajaxurl = "<?php echo admin_url( \'admin-ajax.php\' ); ?>";
var dataArray = <?php echo json_encode($current_posts_ids) ?>;
function getMyPosts() {
data = { action: "update_news", data: dataArray};
$.post(ajaxurl, data, function(response) {
// reset array
dataArray = [];
// append the new news posts
$(\'.latest-news .posts\').append(response);
// create new array of ids to exclude
$(\'article\').each(function(){
dataArray.push($(this).data(\'id\'));
});
// repeat function after 5 seconds
setTimeout(function () {
getMyPosts();
}, 5000)
});
}
//run the function first time
getMyPosts();
});
</script>
功能。php
add_action( \'wp_ajax_update_news\', \'update_news\' );
add_action(\'wp_ajax_nopriv_update_news\', \'update_news\');
function update_news() {
global $wpdb;
$data = $_POST[\'data\'];
$args = array(
\'post_type\' => \'post\',
\'post_status\' => \'publish\',
\'post__not_in\' => $data,
);
$my_posts = new WP_Query( $args );
if($my_posts->have_posts()) :
while($my_posts->have_posts()) : $my_posts->the_post();
echo "<article data-id=\'".get_the_ID()."\'>";
echo "<h2>" . get_the_title() . "</h2>";
echo "<p>" . get_the_excerpt() . "</p>";
echo "</article>";
endwhile;
endif;
wp_die();
}