Skip to content

Instantly share code, notes, and snippets.

@mikeott
Last active May 26, 2023 07:22
Show Gist options
  • Save mikeott/9f863fa58951639751b7c13a779b6fd6 to your computer and use it in GitHub Desktop.
Save mikeott/9f863fa58951639751b7c13a779b6fd6 to your computer and use it in GitHub Desktop.
Load posts using AJAX on click

Load posts onclick with AJAX.

Add to page template

<div id="post-container">
 /* Post titles will be inserted here */
</div>

<button id="load-more">Load More</button>

Add to functions.php

function enqueue_custom_scripts() {
    wp_enqueue_script('jquery');
    wp_enqueue_script('custom-scripts', get_template_directory_uri() . '/js/custom-scripts.js', array('jquery'), '1.0', true);

    /* Localize the script with the ajaxurl */
    wp_localize_script('custom-scripts', 'my_ajax_object', array('ajaxurl' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');



function load_more_posts() {
    $page = $_POST['page'];

    $args = array(
        'post_type'         => 'post',
        'posts_per_page'    => 3,
        'paged'             => $page,
    );

    $query = new WP_Query($args);

    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post(); ?>
                <h2><?php the_title(); ?></h2>
            <?php
        }
        wp_reset_postdata();
    }

    die();
}
add_action('wp_ajax_load_more_posts', 'load_more_posts');
add_action('wp_ajax_nopriv_load_more_posts', 'load_more_posts');

Add to custom-scripts.js

jQuery(document).ready(function($) {
    var page        = 1;
    var loading     = false;
    var container   = $('#post-container');
    var button      = $('#load-more');
  
    function loadPosts() {
      $.ajax({
        url: my_ajax_object.ajaxurl, /* Use the localised ajaxurl variable */
        type: 'POST',
        data: {
            action: 'load_more_posts',
            page: page
        },
        beforeSend: function() {
            loading = true;
            button.text('Loading...');
        },
        success: function(response) {
            container.append(response);
            page++;
            loading = false;
            button.text('Load More');
        },
        error: function(xhr, status, error) {
            console.log(error);
        }
      });
    }
  
    button.on('click', function() {
      if (!loading) {
            loadPosts();
      }
    });
  });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment