• 15/11/2018 • 5 phút đọc • 11 lượt xem

Load More Posts with AJAX. Step by Step Tutorial. No plugins.

Việt Lâm Coder
Việt Lâm Coder
Senior Fullstack & System Architect • Hotline: 0944.71.4545

Creating Load More button for WordPress is really simple. As an option I will show you how to load more posts on scroll

When my blog subscriber asked me about a such tutorial, I was wondering if there are any other analogue tutorials over the internet. And what I found in Google, surprised me.

Reading all those tutorials one thing becomes clear for me – AJAX is not simple at all. But it is not true!

Step 1. Load more button #

Just skip this step if you want to load more posts on scroll.

We begin with the button HTML. Here is just one main rule – do not show the button if there are not enough posts. We will check it with $wp_query->max_num_pages.

<?php
global $wp_query; // you can remove this line if everything works for you

// don't display the button if there are not enough posts
if ( $wp_query->max_num_pages > 1 )
echo '<div class="misha_loadmore">More posts</div>'; // you can use <a> as well
?>



On the image below you can see that I decided to work with Twenty Seventeen theme because it is well-designed and simple enough.


The load more button styled for Twenty Seventeen WordPress theme.

I inserted the button just under the standart pagination (for TwentySeventeen – index.php line 55), but you can remove it as well. To style the button the according way use CSS below.


.misha_loadmore{
background-color: #ddd;
border-radius: 2px;
display: block;
text-align: center;
font-size: 14px;
font-size: 0.875rem;
font-weight: 800;
letter-spacing:1px;
cursor:pointer;
text-transform: uppercase;
padding: 10px 0;
transition: background-color 0.2s ease-in-out, border-color 0.2s ease-in-out, color 0.3s ease-in-out;
}
.misha_loadmore:hover{
background-color: #767676;
color: #fff;
}


Step 2. Enqueue jQuery and myloadmore.js. Pass query parameters to the script. #


Well, that’s where the magic happens. This small piece of code allows you to pass the according parameters to the script that’s why the button can work on any page – tags, categories, post type archives, search etc.



function misha_my_load_more_scripts() {
 
global $wp_query;
 
// In most cases it is already included on the page and this line can be removed
wp_enqueue_script('jquery');
 
// register our main script but do not enqueue it yet
wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/myloadmore.js', array('jquery') );
 
// now the most interesting part
// we have to pass parameters to myloadmore.js script but we can get the parameters values only in PHP
// you can define variables directly in your HTML but I decided that the most proper way is wp_localize_script()
wp_localize_script( 'my_loadmore', 'misha_loadmore_params', array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
'posts' => json_encode( $wp_query->query_vars ), // everything about your loop is here
'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
'max_page' => $wp_query->max_num_pages
) );
 
wp_enqueue_script( 'my_loadmore' );
}
 
add_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );




If you still do not know, the above code is for your functions.php. And please note, my load more button is adapted for the main loop only. If you need it for a custom loop, ask me in comments.

Step 3. myloadmore.js – what is inside? #


It is a small JS file, actually you can place it anywhere you want, for simpleness I decided to place it just in a theme directory (line 9 of previous code).


I also think that I should give you a choice – a load more button or just load posts by scroll.

Option 1. Load More button


If you choose the option 1, skip the option 2 and vice versa.



jQuery(function($){
$('.misha_loadmore').click(function(){
 
var button = $(this),
data = {
'action': 'loadmore',
'query': misha_loadmore_params.posts, // that's how we get params from wp_localize_script() function
'page' : misha_loadmore_params.current_page
};
 
$.ajax({
url : misha_loadmore_params.ajaxurl, // AJAX handler
data : data,
type : 'POST',
beforeSend : function ( xhr ) {
button.text('Loading...'); // change the button text, you can also add a preloader image
},
success : function( data ){
if( data ) {
button.text( 'More posts' ).prev().before(data); // insert new posts
misha_loadmore_params.current_page++;
 
if ( misha_loadmore_params.current_page == misha_loadmore_params.max_page )
button.remove(); // if last page, remove the button
 
// you can also fire the "post-load" event here if you use a plugin that requires it
// $( document.body ).trigger( 'post-load' );
} else {
button.remove(); // if no data, remove the button as well
}
}
});
});
});




Please note that line 23 can be different for your theme, it depends on your HTML document structure. I think you should know some basic jQuery DOM traversal methods – prev(), next(), parent() etc.

Option 2. No button, just load posts on scroll





jQuery(function($){
var canBeLoaded = true, // this param allows to initiate the AJAX call only if necessary
bottomOffset = 2000; // the distance (in px) from the page bottom when you want to load more posts
 
$(window).scroll(function(){
var data = {
'action': 'loadmore',
'query': misha_loadmore_params.posts,
'page' : misha_loadmore_params.current_page
};
if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ){
$.ajax({
url : misha_loadmore_params.ajaxurl,
data:data,
type:'POST',
beforeSend: function( xhr ){
// you can also add your own preloader here
// you see, the AJAX call is in process, we shouldn't run it again until complete
canBeLoaded = false;
},
success:function(data){
if( data ) {
$('#main').find('article:last-of-type').after( data ); // where to insert posts
canBeLoaded = true; // the ajax is completed, now we can run it again
misha_loadmore_params.current_page++;
}
}
});
}
});
});




Step 4. wp_ajax_ #


This is the AJAX handler function. Insert it to your functions.php file.



function misha_loadmore_ajax_handler(){
 
// prepare our arguments for the query
$args = json_decode( stripslashes( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; // we need next page to be loaded
$args['post_status'] = 'publish';
 
// it is always better to use WP_Query but not here
query_posts( $args );
 
if( have_posts() ) :
 
// run the loop
while( have_posts() ): the_post();
 
// look into your theme code how the posts are inserted, but you can use your own HTML of course
// do you remember? - my example is adapted for Twenty Seventeen theme
get_template_part( 'template-parts/post/content', get_post_format() );
// for the test purposes comment the line above and uncomment the below one
// the_title();
 
 
endwhile;
 
endif;
die; // here we exit the script and even no wp_reset_query() required!
}
 
 
 
add_action('wp_ajax_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_nopriv_{action}




 

Việt Lâm Coder

Việt Lâm Coder

Tác giả bài viết và chuyên gia quản trị website. Nếu bạn gặp khó khăn trong quá trình thực hiện hoặc có nhu cầu thiết kế website, lập trình web app Laravel, hãy liên hệ ngay với tôi qua Hotline / Zalo: 0944.71.4545.

☕ Mời Tác Giả Ly Cà Phê Ấm Lòng

Nếu bài viết này giúp ích cho công việc của bạn, hãy tiếp thêm động lực cho tác giả duy trì kho tri thức bằng một ly cà phê ấm lòng nhé!

Mã QR ủng hộ tác giả
Ngân hàng TMCP Quân Đội (MB Bank)TONG VIET LAM

Có Thể Bạn Quan Tâm

Cách Mở Tab Ẩn Danh Trên Safari MacBook Đơn Giản

Cách mở tab ẩn danh trên Safari MacBook sẽ giúp cho người dùng có thể bảo vệ quyền riêng tư và duyệt web một cách an toà...

Hướng dẫn 5 cách tắt update Windows 11 vĩnh viễn chi tiết nhất

Mặc định Windows 11 sẽ được tự động cập nhật trong nền. Tuy nhiên nếu vì lý do nào đó mà bạn không muốn nhận các bản...

Hướng dẫn trỏ file hosts cho domain trên hệ điều hành Windows

– Làm cách nào để 1 website có thể hoạt động trên Share hosting, VPS, Server mà không cần cấu hình các record DNS cho do...

Kích hoạt Cloudflare Turnstile trong Contact Form 7 chống spam

Cloudflare Turnstile là giải pháp xác thực không dùng CAPTCHA giúp bảo vệ website WordPress khỏi spam một cách nhẹ nhàng...

Cách Sử Dụng DeepSeek R1 Miễn Phí Trong Visual Studio Code Với Cline?

Hãy đối mặt với thực tế: Các trợ lý lập trình AI như GitHub Copilot thì tuyệt vời, nhưng chi phí đăng ký của chúng có th...

Gmail API – Tất cả những gì bạn cần biết - 2025

Nếu bạn đang tìm cách tích hợp Gmail vào các ứng dụng của riêng mình thì Gmail API chính là thứ bạn cần! Gmail là một lự...

Hướng dẫn tạo màn hình desktop ảo bằng Task View trên Surface Windows 11

Việt Lâm Coder sẽ hướng dẫn tạo lập nhiều màn hình desktop ảo bằng Task View trên Surface Windows 11 để sắp xếp các tác...

How to Transfer PuTTY Sessions To Another Windows Machine

his is an user contributed article. PuTTY is a terminal emulator application which can act as a client for the SSH, T...

Hướng dẫn cách kiểm tra cổng đang mở (Check open port) trên linux

Với nhiều năm kinh nghiệm hỗ trợ Khách hàng của Tenten, chúng tôi nhận thấy việc thường xuyên theo dõi kiểm tra hoạt độn...

Kiểm tra tất cả các port mà Cyber Panel đang cần có được mở hay không ?

Để kiểm tra tất cả các port cùng một lúc, bạn có thể sử dụng lệnh: netstat -tulpn | grep -E ':(8090|80|443|21|40110|401...

Hướng dẫn cài đặt KeyHelp Panel

Tóm tắt về KeyHelp Bạn đã có phần cứng tốt nhất cho các dự án Internet của mình nhưng việc quản lý phức tạp, hiệu suất...

Tổng hợp danh sách Control Panel VPS free tốt nhất hiện nay

Control Panel VPS free cung cấp một lựa chọn tuyệt vời cho những người dùng muốn quản lý VPS một cách dễ dàng và hiệ...