-2

I'm trying to use this tutorial but it doesn't work: https://artisansweb.net/load-wordpress-post-ajax/

Correct order is: Post 4, Post 1, Post 3, Post 2. The first 2 posts are OK (before click), but when I click button the results are wrong (Post 2, Post 1 AGAIN) instead of Post 3, Post 2.

This is my code:

PAGE TEMPLATE:

<?php /* Template Name: Ajax */
get_header(); ?>

<div class="entry-content">
    <?php 
    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'orderby' => 'date',
        'order' => 'DESC',
        'posts_per_page' => 2,
        'paged' => 1
    );
    $my_posts = new WP_Query($args);
    if ($my_posts->have_posts()) {
    ?>
        <div class="my-posts">
            <?php while ($my_posts->have_posts()) { $my_posts->the_post(); ?>
                <h2><?php the_title(); ?></h2>
                <?php the_excerpt(); ?>
            <?php } ?>
        </div>
    <?php } ?>
    <button class="loadmore">Load more...</button>
</div>

<script type="text/javascript">
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2;

jQuery('body').on('click', '.loadmore', function() {
    var data = {
        'action': 'load_posts_by_ajax',
        'page': page,
        'security': '<?php echo wp_create_nonce("load_more_posts"); ?>',
        'all_pages': '<?php echo $my_posts->max_num_pages;  ?>'
    };

    jQuery.post(ajaxurl, data, function(response) {
        jQuery('.my-posts').append(response);
        if(page == data['all_pages']) {
            jQuery('.loadmore').fadeOut(400);
        }
        page++;
    });
});

</script>

<?php get_footer(); ?>

FUNCTIONS:

function load_posts_by_ajax_callback() {
    check_ajax_referer('load_more_posts', 'security');
    $paged = $_POST['page'];
    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'orderby' => 'date',
        'order' => 'DESC',
        'posts_per_page' => 2,
        'paged' => $paged
    );
    $my_posts = new WP_Query($args);
    if ($my_posts->have_posts()) {
        while ($my_posts->have_posts()) { $my_posts->the_post(); ?>
            <h2><?php the_title(); ?></h2>
            <?php the_excerpt();
        };
    };
    wp_die();
}

add_action('wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax_callback');
add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_posts_by_ajax_callback');

What is wrong?

0

1) You should really use a separate JS file. 2) Check this guide: https://premium.wpmudev.org/blog/using-ajax-with-wordpress/

  • separate JS file and wp_localize_script didnt help – Marcin Urbańczyk Mar 27 at 10:41

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.