M
M
makboriska2021-10-28 19:00:11
AJAX
makboriska, 2021-10-28 19:00:11

Ajax loading posts, when you click on the button - the button disappears and there are no posts?

There is a loop that displays arbitrary records

$mypost_Query = new WP_Query( array(
            'post_type'        => 'courses',                  # post, page, custom_post_type 
            'post_status'      => 'publish',                       # статус записи 
            'paged' => $paged,
            'posts_per_page'   => 2,                             # кол-во постов вывода/загрузки 
          ) );

          if ( $mypost_Query->have_posts() ) {
            while ( $mypost_Query->have_posts() ) { $mypost_Query->the_post();
              get_template_part('./template-page/content-curse');
            }
          }
          else { echo('<p>Извините, нет записей.</p>'); }
          wp_reset_postdata();
          ?>
 				</div>
         <?php // AJAX загрузка постов ?> 
          <?php if ( $mypost_Query->max_num_pages > 2 ) { ?>
            <script> let this_page = 2; </script>

            <div class="btn-loadmore" title="Загрузить еще"
              data-param-posts='<?php echo serialize($mypost_Query->query_vars); ?>'
              data-max-pages='<?php echo $mypost_Query->max_num_pages; ?>'
              data-tpl='doveryayut'
            >
              <span class="fas fa-redo"></span> Загрузить ещё
            </div>
          <?php } ?>

There is also a js handler
jQuery(function($){

  // AJAX загрузка страниц/записей WP 
  $('.btn-loadmore').on('click', function(){
      let _this = $(this);
      _this.html('<span class="fas fa-redo fa-spin"></span> Загрузка...'); // изменение кнопки 

      let data = {
          'action': 'loadmore',
          'query': _this.attr('data-param-posts'),
          'page': this_page,
          'tpl': _this.attr('data-tpl')
      }

      $.ajax({
          url: '/wp-admin/admin-ajax.php',
          data: data,
          type: 'POST',
          success:function(data){
              if (data) {
                  _this.html('<span class="fas fa-redo"></span> Загрузить ещё');
                  _this.prev().prev().append(data); // где вставить данные 
                  this_page++;                      // увелич. номер страницы +1 
                  if (this_page == _this.attr('data-max-pages')) {
                      _this.remove();               // удаляем кнопку, если последняя стр. 
                  }
              } else {                              // если закончились посты 
                  _this.remove();                   // удаляем кнопку 
              }
          }
    });
});

});

and code from theme functions
// AJAX загрузка постов 
function load_posts () {
    $args = unserialize( stripslashes( $_POST['query'] ) );
    $args['paged'] = $_POST['page'] + 1; // следующая страница 

    query_posts( $args );
    if ( have_posts() ) {
        while ( have_posts() ) { the_post();

            if ($_POST['tpl'] === 'courses') {
                get_template_part( '/template-page/content-curse');
            }
      if ($_POST['tpl'] === 'courses') {
                get_template_part( '/template-page/content-curse');
            }
        }
        die();
    }
}
add_action('wp_ajax_loadmore', 'load_posts');
add_action('wp_ajax_nopriv_loadmore', 'load_posts');


When you click on the "Load more" button, the button disappears, but there are no records, while I tried to increase the number of records on the page to their real number and the button disappeared by itself, i.e. the script determines how many records, but it does not work properly So maybe I screwed up somewhere?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question