0

I really hope that someone can help. I would like to load random posts on the homepage when a "LOAD NEW MESSAGE" button is clicked.

We have 200 short messages loaded as posts in Wordpress. ON the homepage we would like people to be able to click a button to reload new messages - but without the page being refreshed.

Please can someone help with how to do this?

Thank you for your time. AB

  • How familiar are you with Ajax / Jquery and WordPress functions such as get_post and / or WP_Query? Have you tried anything so far? – Howdy_McGee Apr 2 '14 at 15:01
  • Hi @Howdy_McGee. I am very familiar with WordPress php. It is ajax/jquery where I fall short. I can load standard loops randomly etc no problem - it is being able to do it with ajax/jquery where I have the issue. Your help would be so apprecaited if possible. – Andrew Brown Apr 2 '14 at 15:04
  • Did you read AJAX in Plugins? – Nicolai Apr 2 '14 at 15:22
2

I've been playing with ajax for the past couple days - I like to go the hook route so first lets set up our ajax call:

$('#buttonID').click(function(){
    $.ajax({
        url: '/wp-admin/admin-ajax.php',
        type: 'GET',
        data: {
            'action' : 'implement_ajax'
        },
        dataType: 'html'
    })
    .success(function(results){
        $('#ContentWrapper').html(results);
    })
    .fail(function( jqXHR, textStatus ) {
        console.log( "Request failed: " + textStatus );
    });
});

the action is what you want to call you ajax function - you can put this in the functions file:

function implement_ajax() {

    $ajaxQuery = new WP_Query(array('post_type' => 'post', 'posts_per_page' =>9, 'orderby' => 'rand'));

    ob_start();

    if($ajaxQuery->have_posts()) : 
        while($ajaxQuery->have_posts()) : $ajaxQuery->the_post(); 
    ?>

        <h1>Title: <?php the_title(); ?></h1>
        <?php /** Normal Loop Stuff **/ ?>

    <?php
        endwhile;
    endif;

    $htmlContent = ob_get_clean();
    echo $htmlContent;
    exit;
}
add_action('wp_ajax_nopriv_implement_ajax', 'implement_ajax');
add_action('wp_ajax_implement_ajax', 'implement_ajax');

We call ob_start to record everyting we echo out, all our html and variables so it doesn't get returned back to our ajax call prematurely. Then we clean it all up via ob_get_clean() and return out html content to our ajax call where we can then just stick anywhere.

Once brought back you can put some fancy smancy fade in animation on it or whatever you need to make it look cool :D !

| improve this answer | |
1

This is just a similar example that would do something you have question about. Every time the user clicks a button it would load random posts.

HTML:

<input type="button" id="load" value="Load random posts" />
<div id="posts"></div>

JQuery:

 <script type="text/javascript">
        $(document).ready(function(e) {
                $("#load").on('click', function(){

                    $.post('any_page.php', 
                    function(data){
                        $('#posts').html(data);
                    });
                });
        });
    </script>

Now your any_page.php which will load the post.

any_page.php:

   <?php 

    $args = array(
            'post_type' => 'post',
            'posts_per_page' =>9,
            'orderby' => 'rand'
            );
            $the_query = new WP_Query($args);   

?><?php  if ( $the_query->have_posts() ) { ?>

    <?php while ($the_query->have_posts()) : $the_query->the_post(); ?>

    <?php the_title() . "<br>"; ?>


    <?php endwhile; ?>

<?php
     } else { ?>
       <h2>Oh No!!</h2>
    <p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php    } 
    wp_reset_postdata();      /* Restore original Post Data */

?>

This will only get the title of the posts.If you need posts with thumbnail and content, you'll need to use the_content method. More information about content could be found here

https://codex.wordpress.org/Function_Reference/the_content

I hope this helps

| improve this answer | |
  • Thanks for this. I have tried but it is not working. I have added the html to the index.php page (where I need the messages to appear), the javascript to the footer.php (immediately after wp_footer) and created a new file any_page.php with the php you suggested. But it is not working. Do you know where I am going wrong here? – Andrew Brown Apr 2 '14 at 15:31
  • Can you try putting the jquery code in the index php after the button and div – user48752 Apr 2 '14 at 15:32
  • Thanks - just tried that but still nothing appears. Am I meant to add or change anything to make it work? – Andrew Brown Apr 2 '14 at 15:34
  • I've updated my answer. Try now and it should work – user48752 Apr 2 '14 at 15:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.