Поддержка Проблемы и решения Как правильно вывести посты с ajax?

  • Приветствую! Вывожу посты по клику с помощью аякса. На странице у меня есть пагинация. Общее количество постов у меня 11 на данный момент. 10 постов на первой странице, а остальной на второй. По клику на кнопку, мне нужно подгрузить посты следующих страниц.
    Но, он мне подгружает 10,8,6,4,2 пост… Почему так происходит?

    Вот мои коды:

    JS

    const loadMoreBtn = document.querySelector('#loadmore');
    const postContainer = document.querySelector('#post-container');
    
    window.addEventListener('load', function () {
        if (loadMoreBtn) {
            loadMoreBtn.addEventListener('click', function () {
                const customAction = 'loadmore';
                const sendType = 'POST';
    
                let postData = new FormData();
    
                postData.append('action', customAction);
                postData.append('query', post_data);
                postData.append('paged', current_page);
    
                const xhr = new XMLHttpRequest();
    
                xhr.open(sendType, ajaxurl);
    
                this.innerText = 'Посты загружаются...';
                this.disabled = true;
    
                xhr.addEventListener('readystatechange', function (data) {
                    if (this.readyState === 4 && this.status === 200) {
                        console.log(data);
    
                        postContainer.innerHTML = data.target.responseText;
    
                        loadMoreBtn.innerText = 'Загрузить еще';
                        loadMoreBtn.disabled = false;
    
                        current_page++;
    
                        console.log(current_page);
    
                        if (current_page >= max_pages) {
                            loadMoreBtn.remove();
                        }
                    }
                });            
    
                xhr.send(postData);
            })
        }
    })
    

    PHP

    	function loadmore_get_posts(){
    		$data = json_decode(stripslashes($_POST['query']));
    		$data['paged'] = $_POST['paged'];
    
    		query_posts($data);
    		
    		if(have_posts()) :
    			while(have_posts()): the_post();    
    			the_post();?>
    			
    			<div class="news__table-item">
                    <div class="news__table-img-container">
                        <img src="<?php the_post_thumbnail_url(); ?>" alt="Картинка новости" class="news__table-img"> 
                    </div>
    				<div class="news__table-content">
    					<span class="news__table-category">
    						<?php
    							foreach((get_the_category()) as $category) {
    								echo $category->cat_name . ' ';
    							}
    						?> 
    					</span>
    					<a href="<?php the_permalink(); ?>" class="news__table-title">
    						<?php the_title(); ?>
    					</a>
    					<p class="news__table-desc">
    						<?php the_content(); ?>
    					</p>
    					<div class="news__table-date">
    						<?php the_date(); ?>
    					</div>
    				</div>
    			</div>
    			
    			<?php			
    			endwhile;
    		endif;
    		wp_die();
    	}
    	 
    	add_action('wp_ajax_loadmore', 'loadmore_get_posts');
    	add_action('wp_ajax_nopriv_loadmore', 'loadmore_get_posts');

    Вывод данных в теге script

                        <script>
                            let ajaxurl = '<?php echo admin_url('admin-ajax.php') ?>';
                            let current_page = <?php echo (get_query_var('paged')) ? get_query_var('paged') : 1; ?>;
                            let max_pages = <?php echo $custom_query->max_num_pages ?>;
                            let post_data = <?php echo json_encode($custom_query->query_vars); ?>;
                        </script>
    
  • Тема «Как правильно вывести посты с ajax?» закрыта для новых ответов.