Load More Posts via Ajax in WordPress
Implementing an "Load More" button to dynamically load posts in WordPress requires a combination of PHP and JavaScript. While you've outlined a particular approach, there may be additional factors that influence the functionality or efficiency of your code. Here's a revised and enhanced solution:
HTML Markup:
<div>
Functions PHP File:
function more_post_ajax() { $offset = $_POST["offset"]; $ppp = $_POST["ppp"]; header("Content-Type: text/html"); $args = [ 'suppress_filters' => true, 'post_type' => 'post', 'posts_per_page' => $ppp, 'cat' => 1, 'offset' => $offset, ]; $loop = new WP_Query($args); while ($loop->have_posts()) { $loop->the_post(); the_content(); } exit; } add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax'); add_action('wp_ajax_more_post_ajax', 'more_post_ajax'); wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array( 'ajaxurl' => admin_url('admin-ajax.php'), 'noposts' => __('No older posts found', 'twentyfifteen'), ) );
jQuery Function:
var ppp = 3; // Posts per page var page = 5; // Current page number, starting from 1 $('#more_posts').click(function() { $('#more_posts').attr('disabled', true); var offset = (page * ppp) + 1; $.post( ajax_posts.ajaxurl, { action: 'more_post_ajax', offset: offset, ppp: ppp, } ).success(function(posts) { page++; $('#ajax-posts').append(posts); $('#more_posts').attr('disabled', false); }); });
Additional Considerations:
The above is the detailed content of How to Implement Ajax-Powered \'Load More\' Posts in WordPress?. For more information, please follow other related articles on the PHP Chinese website!