Skip to content

Instantly share code, notes, and snippets.

@krystyna93
Created June 16, 2023 14:05
Show Gist options
  • Save krystyna93/2b5e4ffef7e35bcc196e622531b4ac88 to your computer and use it in GitHub Desktop.
Save krystyna93/2b5e4ffef7e35bcc196e622531b4ac88 to your computer and use it in GitHub Desktop.
WordPress 'Load More' Functionality w/o Ajax
<?php
function load_more_scripts() {
wp_enqueue_script( 'load-more', get_stylesheet_directory_uri() . '/js/load-more.js', array('jquery'), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'load_more_scripts' );
function load_more_posts() {
check_ajax_referer( 'load_more_security', 'security' );
$paged = $_POST['page'];
$post_type = isset($_POST['post_type']) ? $_POST['post_type'] : 'post';
$query_args = array(
'post_type' => $post_type,
'post_status' => 'publish',
'posts_per_page' => 5,
'paged' => $paged,
);
if (is_archive()) {
$query_args['post_type'] = get_queried_object()->name;
}
$query = new WP_Query($query_args);
while ( $query->have_posts() ) : $query->the_post();
// Output your post content here
endwhile;
wp_die();
}
add_action( 'wp_ajax_load_more_posts', 'load_more_posts' );
add_action( 'wp_ajax_nopriv_load_more_posts', 'load_more_posts' );
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$query = new WP_Query( array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 5,
'paged' => $paged,
));
?>
<div id="post-container">
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<!-- Output your post content here -->
<?php endwhile; ?>
</div>
<?php if ($query->max_num_pages > 1) : ?>
<div id="load-more-wrapper">
<a href="<?php echo next_posts($query->max_num_pages, false); ?>" class="load-more" data-nonce="<?php echo wp_create_nonce( 'load_more_security' ); ?>">Load More Posts</a>
</div>
<?php endif; ?>
<?php wp_reset_postdata(); ?>
jQuery(document).ready(function($) {
$('#load-more-wrapper').on('click', '.load-more', function(e) {
e.preventDefault();
var nextlink = $(this).attr('href');
var nonce = $(this).data('nonce');
$('#post-container').append('<div class="loading-indicator"><span>Loading...</span></div>');
$.ajax({
url: nextlink,
type: 'POST',
dataType: 'html',
data: {
action: 'load_more_posts',
security: nonce,
page: $(this).data('page'),
post_type: $(this).data('post-type'),
},
success: function(data) {
var posts = $(data).find('#post-container').html();
$('#post-container').append(posts);
$('.loading-indicator').remove();
},
});
});
});
/* code uses WordPress's wp_create_nonce() function to generate a unique security token for each request, and verifies it
using the check_ajax_referer() function to prevent unauthorized access to your server. */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment