certainlyakey
1/17/2017 - 10:07 PM

Load more posts via ajax — basics

Load more posts via ajax — basics

  $('.c-logo').click(function() {
    $.ajax({
      url: ajaxurl,
      type: 'POST',
      data: {
        'action' : 'mytheme_loadmore_posts_ajax',
        'offset' : 2
      },
      success:function(data) {
        console.log(data);
      }
    });

    return false;
  });
<script type="text/javascript">
    ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php 
function mytheme_loadmore_posts_ajax_callback() {
  $args = array( 'post_type' => 'post', 'offset' => $_POST['offset'] );
  $loop = new WP_Query( $args );
  while ( $loop->have_posts() ) : $loop->the_post();
    the_title();
    echo '<div class="entry-content">';
    the_content();
    echo '</div>';
  endwhile;
  wp_die();
  // or with Timber:
  // $args = array( 'post_type' => 'post', 'offset' => $_POST['offset'] );
  // $posts = Timber::get_posts($args);
  // foreach($posts as $post) {
    // $context['post'] = $post;
    // Timber::render('partials/image-teaser.twig', $context);
  // }
  // wp_die();
}

add_action( 'wp_ajax_mytheme_loadmore_posts_ajax', 'mytheme_loadmore_posts_ajax_callback' );
add_action( 'wp_ajax_nopriv_mytheme_loadmore_posts_ajax', 'mytheme_loadmore_posts_ajax_callback' );