Load more functionality
Blog site is increasing day by day.Maximum people are using wordpress for creating blog and publishing their article everyday. When so many articles are published in a blog. It is not possible to show all article for first time page load. So it will take to much time to load all the article. So if we load the article first time 5 or 6 and then click to a button load next 5 or 6 post. It will take less time to load the article. In this case, we are using jquery ajax for that and call WordPress core ajax file for that. Before going to this post, we have to understand the process of ajax implementation in wordpress.
First load first 6 article:
$args = array( 'post_type' => 'post', 'post_status' =>'publish', 'posts_per_page' => 6, 'paged' => 1 ); $query = new WP_Query($args); $posts = $query->posts; foreach($posts as $val) { //Do your design }
Here posts_per_page is used to load first time how many article will be loaded and paged is use to which page is this means first page or second page like pagination.
Now call button click function in javascript.
<button type="button" name="load more" onclick="load_more">Load More</button>
Now declaring click function and use jquery ajax function to load more article.
<script> var paged=1; function load_more(){ paged++; var ajaxurl = "<?php echo admin_url('admin-ajax.php')?>"; var str = '&paged=' + paged + '&action=load_more_article'; $.ajax({ type: "POST", dataType: "html", url: ajaxurl, data: str, success: function(data){ //Append the return data to your view position } }); } </script>
Now go to your function page or plugin page and use the following code to load more article.
<?php add_action('wp_ajax_nopriv_load_more_article','load_more_article'); add_action('wp_ajax_load_more_article', 'load_more_article'); function load_more_article(){ $paged = (isset($_POST["paged"])) ? $_POST["paged"] : ''; $args = array( 'post_type' => 'post', 'post_status'=>'publish', 'posts_per_page' =>6, 'paged' => $paged ); $query = new WP_Query($args); $posts = $query->posts; foreach($posts as $val) { //Design your article code and return to view page. } } ?>
After getting the next 6 article in ajax success method, append the article to your main div. That it.
Conclusion
If you like our post and if you think this post is helpful, then share this post in social media.