Load the next page of posts without reloading the page. This example requires the lotgrafixData object from the wp_localize_script() post.

functions.php

function lotgrafix_load_more() {
    check_ajax_referer( 'lotgrafix_nonce', 'nonce' );

    $paged = isset( $_POST['page'] ) ? absint( $_POST['page'] ) : 1;

    $query = new WP_Query( array(
        'post_type'      => 'post',
        'post_status'    => 'publish',
        'posts_per_page' => 6,
        'paged'          => $paged,
    ) );

    ob_start();
    while ( $query->have_posts() ) {
        $query->the_post();
        echo '<article><h3><a href="' . esc_url( get_permalink() ) . '">' . esc_html( get_the_title() ) . '</a></h3></article>';
    }
    wp_reset_postdata();

    wp_send_json_success( array(
        'html'     => ob_get_clean(),
        'max_page' => $query->max_num_pages,
    ) );
}
add_action( 'wp_ajax_lotgrafix_load_more', 'lotgrafix_load_more' );
add_action( 'wp_ajax_nopriv_lotgrafix_load_more', 'lotgrafix_load_more' );

HTML

<div class="lotgrafix-posts"><!-- First page of posts --></div>
<button class="lotgrafix-load-more">Load More</button>

main.js

var button = document.querySelector( '.lotgrafix-load-more' );
var container = document.querySelector( '.lotgrafix-posts' );
var page = 1;

if ( button && container ) {
    button.addEventListener( 'click', function () {
        page++;

        fetch( lotgrafixData.ajaxUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: new URLSearchParams( {
                action: 'lotgrafix_load_more',
                nonce: lotgrafixData.nonce,
                page: page,
            } ),
        } )
            .then( function ( r ) {
                return r.json();
            } )
            .then( function ( res ) {
                if ( ! res.success ) {
                    return;
                }
                container.insertAdjacentHTML( 'beforeend', res.data.html );
                if ( page >= res.data.max_page ) {
                    button.remove();
                }
            } );
    } );
}
«
»