You can create a function for your ajax request, and set a timeout so it repeats. You will also need to send the ids of the current news articles being displayed so you can exclude them from your new WP_Query in your PHP
UPDATED – This now uses a data attribute to create an array of post ids to exclude off the next ajax request.
live.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>
function.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();
}