themes

Create AJAX Load More Posts in WordPress

Implement an AJAX-powered “Load More” feature to dynamically load additional testimonial posts without refreshing the page.

/*Load more */
function more_post_ajax(){
   $total_count = 0;
   $ppp=5;
   $args = array(
        'post_status' => 'publish',
        'post_type' => 'testimonials',
        'posts_per_page' => $ppp,
        'order' => 'DESC',
        
    );
    $result = array();
    $loop = new WP_Query($args);
    $result['result'] = '';
    if(isset($_POST['offset']) && !empty($_POST['offset'])) {
      $args['offset'] = $_POST['offset'];
    }
    
  $Media_query = new WP_Query($args);
  $result['result'] = '';
   if( $Media_query->have_posts() ) 
      { 
        while ($Media_query->have_posts()) 
        {
          $Media_query->the_post();
          $params['post_id'] = get_the_ID();
          $result['result'] .= qrs_return_get_template_part( 'template-parts/content', 'testimonials-list',$params);
        }      
      }
    
    
    $result['offset'] = $ppp + $_POST['offset'];
    $result['total_post'] = $Media_query->found_posts;
    $result['query'] = $Media_query->request;
    echo json_encode($result);
    exit;  
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');



Leave a reply

Your email address will not be published. Required fields are marked *