1

i have pieced together a post grid loop with AJAX Load More button for posts from a CPT category but I cant get the offset to work properly. There are supposed to be 6 posts per page but at the moment it loads the next 6 posts in random order and duplicates some of them. Also I need the button to disappear when there are no more posts to load, i cant find how to do this anywhere!

Template code:

<?php 
    $postsPerPage = 6;
    $args = array(
        'post_status' => 'publish',
        'post_type' => 'ce_project',
        'posts_per_page' => $postsPerPage,
        'offset' => $offset,
        'category_name' => 'branding',
        'order' => 'DESC'
    ); ?>
          <div class="tabgrid">
          

  <?php  $loop = new WP_Query($args);

    while ($loop->have_posts()) : $loop->the_post();
?>
<?php get_template_part( 'template-parts/content-postgrid' ); ?>
<?php endwhile; ?>

<?php wp_reset_postdata(); ?>

           </div>
           <div class="loadmore-row"><a id="more_posts"></a></div>

Functions.php:

function more_post_ajax(){
    $offset = $_POST["offset"];
    $ppp = $_POST["ppp"];
    header("Content-Type: text/html");

    $args = array(
        'post_type' => 'ce_project',
        'posts_per_page' => $ppp,
        'offset' => $offset,
        'order' => 'DESC'
    );

    $loop = new WP_Query($args);
    while ($loop->have_posts()) { $loop->the_post(); 
      get_template_part( 'template-parts/content-postgrid' );
    }

    exit; 
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax'); 
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

JS:

jQuery(document).ready(function($){
     
    var ajaxUrl = "http://example.com/wp-admin/admin-ajax.php";
    var page = 1; // What page we are on.
    var ppp = 6; // Post per page

    $("#more_posts").on("click",function(){ // When btn is pressed.
        $("#more_posts").attr("disabled",true); // Disable the button, temp.
        $.post(ajaxUrl, {
            action:"more_post_ajax",
            offset: (page * ppp) + 1,
            ppp: ppp
        }).success(function(posts){
            page++;
            $(".tabgrid").append(posts); // CHANGE THIS!
            $("#more_posts").attr("disabled",false);
        });

   });
});
0

Use this below code it will work as I have used this and working fine at my end.

<?php

$querystr = "
    SELECT * FROM $wpdb->posts
    LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
    LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
    LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)
    WHERE $wpdb->terms.slug = 'branding'
    AND $wpdb->term_taxonomy.taxonomy = 'taxonomy_name'
    AND $wpdb->posts.post_status = 'publish'
    AND $wpdb->posts.post_type = 'ce_project'
    ORDER BY $wpdb->posts.post_date DESC";
    
    $result1 = $wpdb->get_results($querystr);
    $totalPosts = count($result1);

$querystr2 = "
    SELECT * FROM $wpdb->posts
    LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
    LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
    LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)
    WHERE $wpdb->terms.slug = 'branding'
    AND $wpdb->term_taxonomy.taxonomy = 'taxonomy_name'
    AND $wpdb->posts.post_status = 'publish'
    AND $wpdb->posts.post_type = 'ce_project'
    ORDER BY $wpdb->posts.post_date DESC LIMIT 0,6";
    
    $result2 = $wpdb->get_results($querystr2);
    
    foreach($result2 as $post){
        
        echo '<h2 class="search-item__title">'.get_the_title($post->ID).'</h2>';
        
    }
?>

<input type="hidden" id="row" value="0" />
<input type="hidden" id="all" value="<?php echo $totalPosts; ?>" />
<input type="hidden" id="taxonomy" value="taxonomy_name" />
<input type="hidden" id="term_id" value="branding" />

<div class="loader" style="display:none;"><img src="<?php echo get_template_directory_uri(); ?>/images/loader-fading.gif" alt="loading.." /></div>

<script>
$(document).ready(function(){
 //alert('dfd');
 $(window).scroll(function(){
 
  var position = $(window).scrollTop() + 1;
  var bottom = $(document).height() - $(window).height();
  
    console.log('Position: '+position);
  console.log('Bottom: '+bottom);
  
  if( position > bottom ){
   var row = Number($('#row').val());
   var allcount = Number($('#all').val());
   var taxonomy = $('#taxonomy').val();
   var term_id = $('#term_id').val();   
   var rowperpage = 10;
   row = row + rowperpage;

   if(row <= allcount){
        $('#row').val(row);
        jQuery(".loader").css('display','block');
        row = "row=" + row + "&cat_name=" + taxonomy + "&cat_id=" + term_id + "&action=get_archive";
        $.ajax({
         type: 'POST',
         url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
         data: row,
         success: function(response){
            //console.log(response);
            setTimeout(function(){ 
                $(".search-item:last").after(response).show().fadeIn("slow");
                $(".loader").css('display','none');
            }, 1000);
            
         }
        });
   }
  }

 });
 
});
</script>

<?php
// copye and paste the below function in functions.php file.
// AJAX request for auto load listing
function get_archive(){
    global $wpdb;
    
    $html = '';
    $row = $_POST['row'];
    $cat_name = $_POST['cat_name'];
    $cat_id = $_POST['cat_id'];
    $rowperpage = 6;

    $querystr2 = "
    SELECT * FROM $wpdb->posts
    LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
    LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
    LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)
    WHERE $wpdb->terms.slug = '".$cat_id."'
    AND $wpdb->term_taxonomy.taxonomy = '".$cat_name."'
    AND $wpdb->posts.post_status = 'publish'
    AND $wpdb->posts.post_type = 'ce_project'
    ORDER BY $wpdb->posts.post_date DESC LIMIT ".$row.",".$rowperpage."";
    
    $result2 = $wpdb->get_results($querystr2);

    // Check form ajax action 
    if($_POST['action'] == 'get_archive')
    {
        
        foreach($result2 as $post){

            $html .= '<h2 class="search-item__title">'.get_the_title($post->ID).'</h2>';
                
        }       

        echo $html;
    }
    else
    {
        echo "error";
    }

exit;
}
add_action( 'wp_ajax_get_archive', 'get_archive' );
add_action( 'wp_ajax_nopriv_get_archive', 'get_archive' );
?>
2
  • Thanks I tried to implement this but it displays nothing. I don't think it is the solution for me. it should loop "get_template_part( 'template-parts/content-postgrid' );" also i dont see here where the 'load more' button is placed?? sorry!
    – Agxer
    Jul 30 '20 at 0:25
  • You can customize the loop or post types/taxonomy as per your need. Regarding, the load more button you can add a button and call the ajax onClick of button. My code is for auto scroll loading results and its working fine at my end..
    – AAKASH9820
    Jul 30 '20 at 11:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.