Introduction :
In this article, I will give you a starting point to create an AJAX interaction with your WordPress site. Ajax has become a fury in recent years and for the cause. Ajax (Asynchronous JavaScript and XML) is a way to interact with the server and see the results without having to reload the page. In this article includes the enqueue scripts, the configuration of the of AJAX handler, create your own WordPress shortcodes, The features of WordPress and the access the database, and the Logic of Loading posts in the User Page.
Why do we use Ajax?
When loads the first page of WordPress site, it will load all the post data and used to loop to show the markup as we have added. Apart from navigation menus, widgets, graphics and other media, JavaScript files, style sheets and a lot of other things are loaded.
Suppose when we try to access the second page of our posts, everything happens again like above. It also burdens all the peripheral elements of the page. In Many cases (but not in all), this supposes a waste of bandwidth and damages the user’s experience. After all, nobody likes it Wait for a load of that page.
1. Create a Word Press short code (i.e [ajax_posts]) we are goin to use same on pages/templates :
Word Press shortcode API works very simply, first you need to create a callback function that will be executed every time you use the code, so you need to associate this function with a specific short code that makes it ready for use.
a). Short code callback function to display initial posts at WordPress active theme functions.php file. Ex : /wp-content/themes/twentyseventeen/functions.php
1 2 3 4 5 6 7 8 9 10 11 12 |
/* * initial posts dispaly */ function script_load_more($args = array()) { //initial posts load echo '<div id="ajax-primary" class="content-area">'; echo '<div id="ajax-content" class="content-area">'; ajax_script_load_more($args); echo '</div>'; echo '<a href="#" id="loadMore" data-page="1" data-url="'.admin_url("admin-ajax.php").'" >Load More</a>'; echo '</div>'; } |
b). The WordPress hooks we used for add_shortcode ( tag, callable) Now Let’s call our action “script_load_more” function at active theme functions.php file. Ex : /wp-content/themes/twentyseventeen/functions.php
1 2 3 4 |
/* * create short code. */ add_shortcode('ajax_posts', 'script_load_more'); |
2. Create WordPress custom handlers for your own custom AJAX requests:
The WordPress hooks we used for ajax calls wp_ajax_{action} and wp_ajax_nopriv_{action}. Now Let’s call our action “ajax_script_load_more”,
a). Create a callback function to to load posts at WordPress active theme functions.php file.Ex : /wp-content/themes/twentyseventeen/functions.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
/* * load more script call back */ function ajax_script_load_more($args) { //init ajax $ajax = false; //check ajax call or not if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { $ajax = true; } //number of posts per page default $num =5; //page number $paged = $_POST['page'] + 1; //args $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' =>$num, 'paged'=>$paged ); //query $query = new WP_Query($args); //check if ($query->have_posts()): //loop articales while ($query->have_posts()): $query->the_post(); //include articles template include 'ajax-content.php'; endwhile; else: echo 0; endif; //reset post data wp_reset_postdata(); //check ajax call if($ajax) die(); } |
b).Create a template “ajax-content.php” at active theme directory to format posts, we used same file in our ajax callback function “ajax_script_load_more”. Ex : /wp-content/themes/twentyseventeen/ajax-content.php
1 2 3 4 5 6 7 8 |
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <?php the_title( '<h3 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h3>' );?> </header> <div class="entry-content"> <?php the_content( 'Continue reading... ' . get_the_title() ); ?> </div> </article> |
c).Create a ajax action hook to call “ajax_script_load_more” function to to load posts at WordPress active theme functions.php file. Ex : /wp-content/themes/twentyseventeen/functions.php
1 2 3 4 5 |
/* * load more script ajax hooks */ add_action('wp_ajax_nopriv_ajax_script_load_more', 'ajax_script_load_more'); add_action('wp_ajax_ajax_script_load_more', 'ajax_script_load_more'); |
3. Create new file named “script_ajax.js” at WordPress active theme js directory nd enqueue the same file on WordPress active theme functions.php
Ex1 : /wp-content/themes/twentyseventeen/js/script_ajax.js.
Ex2 : /wp-content/themes/twentyseventeen/functions.php
1 2 3 4 5 6 7 8 9 10 |
/* * enqueue js script */ add_action( 'wp_enqueue_scripts', 'ajax_enqueue_script' ); /* * enqueue js script call back */ function ajax_enqueue_script() { wp_enqueue_script( 'script_ajax', get_theme_file_uri( '/js/script_ajax.js' ), array( 'jquery' ), '1.0', true ); } |
Here i am giving two options with js code any one you can use the other one skip.
a). Load posts when user clicks the Load More button
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
jQuery.noConflict($); /* Ajax functions */ jQuery(document).ready(function($) { //onclick $("#loadMore").on('click', function(e) { //init var that = $(this); var page = $(this).data('page'); var newPage = page + 1; var ajaxurl = that.data('url'); //ajax call $.ajax({ url: ajaxurl, type: 'post', data: { page: page, action: 'ajax_script_load_more' }, error: function(response) { console.log(response); }, success: function(response) { //check if (response == 0) { $('#ajax-content').append('<div class="text-center"><h3>You reached the end of the line!</h3><p>No more posts to load.</p></div>'); $('#loadMore').hide(); } else { that.data('page', newPage); $('#ajax-content').append(response); } } }); }); }); |
b).Load more posts as the user scrolls the page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
jQuery.noConflict($); /* Ajax functions */ jQuery(document).ready(function($) { //find scroll position $(window).scroll(function() { //init var that = $('#loadMore'); var page = $('#loadMore').data('page'); var newPage = page + 1; var ajaxurl = $('#loadMore').data('url'); //check if ($(window).scrollTop() == $(document).height() - $(window).height()) { //ajax call $.ajax({ url: ajaxurl, type: 'post', data: { page: page, action: 'ajax_script_load_more' }, error: function(response) { console.log(response); }, success: function(response) { //check if (response == 0) { //check if ($("#no-more").length == 0) { $('#ajax-content').append('<div id="no-more" class="text-center"><h3>You reached the end of the line!</h3><p>No more posts to load.</p></div>'); } $('#loadMore').hide(); } else { $('#loadMore').data('page', newPage); $('#ajax-content').append(response); } } }); } }); }); |
Conclusion :
Shortcodes are great, we can use our shortcode “ajax_posts” to load more posts on wordpress pages or page templates.
a). On WordPress pages use following short code tag to load more posts ex : [ajax_posts]
b). On WordPress page templates use below code.
1 2 3 |
<?php echo do_shortcode('[ajax_posts]'); ?> |
Thank you for great job! This code was only working solution for me 🙂
Thanks Adam, please subscribe my blog for more interesting updates.
It works perfectly! Thank you so much
Thanks Allsson, please subscribe my blog for more interesting updates.
Hi, thanks for your article.
My only question is in which file should I place the last code you give with the two available options (scroll or button).
I’m sorry, I do not know much about this.
PD Sorry for my bad English
Thanks Larii,
place your javascript code on “script_ajax.js” file, i mentioned same on above point three.
3. Create new file named “script_ajax.js” at WordPress active theme js directory and enqueue the same file on WordPress active theme functions.php
Ex1 : /wp-content/themes/twentyseventeen/js/script_ajax.js.
, please subscribe my blog for more interesting updates.
Really thanks for a working code,
I spent a lot of time to search “load more” related articles
but this is perfectly working for me.
Thanks for your comment.
Glad to help you.
Keep visiting for more such informational posts.
Dear Satvik !
Your gadget is working fine for me . Only one problem after deploying above code is that I lost the functionality of an ajax based widget on the same page. When I hit the older or newer link of my widget the whole widget disappear rather than showing next posts. The complete code of that widget is as below:
query(‘post_type=post&showposts=3′.’&paged=’.$paged);
?>
have_posts()) : $new_query->the_post(); ?>
max_num_pages) ?>
jQuery(function($) {
$(‘#content’).on(‘click’, ‘#pagination a’, function(e){
e.preventDefault();
var link = $(this).attr(‘href’);
$(‘#content’).fadeOut(500, function(){
$(this).load(link + ‘ #content’, function() {
$(this).fadeIn(500);
});
});
});
});
Interesting thing is that when I remove the short code of your widget from the page my widget works fine again.
I want to use both snippets working on the same page.
Please Share your experience.
Thanks.
Hi Shahid,
Thanks for your comment, it’s mostly JavaScript conflicts between your code and my code please check carefully both codes and change ids or events, you will find a solution. Keep visiting for more such informational posts.
What if i would like to specify a category, how could i do this?
excelente tutorial!
Hi Cesar,
Glad to help you, Just add your category condition to WP_Query, you will get all posts based on your category. Keep visiting for more such informational posts.
Ref : https://codex.wordpress.org/Class_Reference/WP_Query
but if i would like it to be in the short code, i’ve been trying to do so but i get repeated post or i get a post from another category.
Hi,
Infinite scroll is working fine but same 3 posts is repeating again & again in an infinite scroll..can you please help me with this…asap!!!
Thank you in advance…
Hi Parul,
Glad to help you, Please check what value you get in “$ paged = $ _POST [‘page’] + 1;” here every time you press the “load more” value will increase to show the next post. If the value does not rise then your javascript may be broken or some error in code.
Ex : /wp-content/themes/twentyseventeen/functions.php
function ajax_script_load_more($args) {
//code
echo $paged = $_POST['page'] + 1; // or view the firebug console ajax call post parameters
//code
}
However, if you are unable to fix this issue, then ping me scripthere.com FB page (https://www.facebook.com/blogscripthere/) I’ll help you out on it.
Thank you for your quick response…I will try to figure it out and will contact you in case its not done.
Thanks
Good thing !! this is absolutely helpful thanks for sharing.
Thanks a lot bro, that’s the only one example that I implemented successfully after days of deep research in the subject, anyway I’m having a little issue. When I click on the load more button the scrollbars get freezed and doesn’t recognize the new height of the page, do you have any idea why that happens?
It can be any other block of external scripts, check if you can not figure, please share details on my fb page, I will help you in this.
Great post great working. Thanks
I use this on my site, I only have one issue, in android browsers (chrome and firefox) the “if” on check don’t work on scroll detection, I change to this “if ($(window).scrollTop() == $(document).outerHeight() – $(window).height() -56 ) {” and before of it, used an android detector, the “-56” is because the bar of navigation add 56px in the height.
Thanks
Hi, I’m getting this notice come up when using this (using the load more option, not infinite scrolling)
Notice: Undefined index: page in the functions.php
Could you advise?
Thanks!
try to add isset check for $_POST[‘page’]
ex : $_page = (isset($_POST[‘page’]))?$_POST[‘page’] : 0;
Thank you so much for this article. Very useful.