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

wordpress load more posts button

Bài viết này thực hiện (hoặc lụm bài về đăng câu like từ các trang khác) bởi Việt Lâm Coder một YOUTUBER có tâm và đẹp trai siêu cấp vô địch zũ trụ.

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.

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

Load More Posts with AJAX. Step by Step Tutorial. No plugins.
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.

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.

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.

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

Step 4. wp_ajax_ #

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

 

Bài viết này thực hiện (hoặc lụm bài về đăng câu like từ các trang khác) bởi Việt Lâm Coder một YOUTUBER có tâm và đẹp trai siêu cấp vô địch zũ trụ.

Liên hệ ngay với Việt Lâm Coder
Xin chào! Chúng tôi có thể giúp gì cho bạn ?
Gọi ngay cho chúng tôi