questions

Show random post in WP and update content without refreshing page

Rate this post

I’m building a WordPress website where I need to display a random post (via WP_Query) and reload its content with a click of a button without refreshing the whole page.

This is my HTML

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

And this is my 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; ?>

I’ve read online about AJAX but I’m not that great at JS development and I could’t find a way to make it work.

 

✔️Solution:

For me the easiest way is to add jQuery reload function. So below your HTML with button, you will add

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

(You also must use jQuery, so if you don’t have it on your page, add <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>)

Leave a Reply

Your email address will not be published.

Back to top button