Site icon Hip-Hop Website Design and Development

load leftover posts when limiting posts load more wordpress

My site uses ajax to load posts according to the load more principle when scrolling. It can be loaded until all posts are loaded. The customer asked to set a limit on the number of uploaded posts. I almost got it. But there is one problem:

Posts are loaded in 8 or 9 posts per scroll. And for example, I limited the download to 20 posts. The problem is that the code will only load a multiple of 8 or 9 posts – 16 or 18. Also, if I limit to 30 posts, then only 24 will be loaded if 8, and 27 posts if 9 are loaded. BUT how to load the rest, I can’t understand ?! Those. the limit is 20, I load 8, in total 16 posts. And the other 4 are not loaded.

Please help solve this problem. Or at least give a hint.

Thanks!

Here is the ajax code:

document.addEventListener("DOMContentLoaded", () => {
        let ajaxurl = '<?php echo admin_url('admin-ajax.php') ?>';
        let section_posts = 1;
        let postData = new FormData();
        let scroll_state = true;
        let loader = document.querySelector('.articlefeed_loader');
        let height_footer = document.querySelector('.site-footer').getBoundingClientRect().height;
        let max_posts = <?php print json_encode(get_limit_val())?>;

        window.addEventListener('scroll', function () {
            if (scroll_state == true) {
                if ((window.innerHeight + window.pageYOffset) >= (document.body.offsetHeight - height_footer)) {   
                    postData.append('action', 'loadmore');
                    postData.append('paged', section_posts);
                    postData.append('posts_per_page', <?php echo $posts_per_page; ?>);
                    postData.append('cats', <?php print json_encode(get_selected_cats())?>);

                    const xhr = new XMLHttpRequest();
                    xhr.open('POST', ajaxurl);
                        xhr.addEventListener('readystatechange', function (data) {
                            if (this.readyState === 4 && this.status === 200) {
                                section_posts++;
                                if (max_posts) {

                                    let mod = max_posts - section_posts * <?php echo $posts_per_page; ?>;
                                    if (max_posts >= section_posts * <?php echo $posts_per_page; ?>) {
                                        document.querySelector('.box').innerHTML += data.target.responseText;
                                    } else {
                                        console.log(Math.abs(mod));
                                        clearTimeout(timeout);
                                    }

                                }
                            } else {}
                        });            
                    xhr.send(postData);
                    scroll_state = false;
                    timeout = setTimeout(function() {
                        scroll_state = true;
                    }, 1000);
                }
            }
        });
    });

These are the hooks in function.php:

function loadmore_get_posts(){
  
  $paged = !empty($_POST['paged']) ? $_POST['paged'] : 1;
    $paged++;

  $args = array(
        'paged' => $paged,
        'posts_per_page' => $_POST['posts_per_page'],
        'post_type'      => 'post',
        'post_status' => 'publish',
        'cat' => $_POST['cats']
  );

  $data = new WP_Query( $args );
 
  while( $data->have_posts() ) : $data->the_post();
    get_template_part( 'templates/...' );   
  endwhile;
  die;
}
add_action('wp_ajax_loadmore', 'loadmore_get_posts');
add_action('wp_ajax_nopriv_loadmore', 'loadmore_get_posts');