S
S
sergey19892015-10-17 16:52:18
CMS
sergey1989, 2015-10-17 16:52:18

On the first page of WordPress pagination there are 9 posts on the other 8 with AJAX underwear?

Good day. When loading posts in WordPress, the task was to make 9 posts on the first page and load 8 posts with each click. I found a similar topic https://toster.ru/q/222186 , but there is a regular pagination without AJAX and in my case this solution does not work. As an option, I’m considering simply hiding the extra element, but displaying it again with a new click, while hiding the last element in the last output, although I understand that such a solution is not entirely competent.

<main class="row">
          <?php 
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
   'posts_per_page' =>
          '9',
          
          'cat' =>
          '1',
);
$wp_query = new WP_Query( $args );
?>
          <?php $loop = 0; ?>
          <?php while ( $wp_query->
          have_posts() ) : $wp_query->the_post();?>
          <article class="col-md-8 col-sm-6">
            <div class="main-news">
              <time>
                <?php the_time( 'j F, Y'); ?></time>
              <div class="image-news hidden-sm hidden-xs">
                <a href="<?php the_permalink(); ?>
                  ">
                  <?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'first-thumb' ); } ?></a>

              </div>
              <div class="image-news hidden-md hidden-lg" style="background: none !important;">
                <a href="<?php the_permalink(); ?>
                  ">
                  <?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'second-thumb' ); } ?></a>
              </div>
              <a href="<?php the_permalink(); ?>
                " class="teaser-news" style="margin-top: -1px;">
                <?php the_title(); ?></a>
            </div>
          </article>

          <?php endwhile;  ?>
          <?php if (  $wp_query->
          max_num_pages > 1 ) : ?>
          <!-- Вывод кнопки подгузить -->
          <script>
  var ajaxurl = '<?php echo site_url() ?>/wp-admin/admin-ajax.php';
  var true_posts = '<?php echo serialize($wp_query->query_vars); ?>';
  var current_page = <?php echo (get_query_var('paged')) ? get_query_var('paged') : 1; ?>;
  var max_pages = '<?php echo $wp_query->max_num_pages; ?>';</script>

          <div class="text-center">
            <button type="button" id="true_loadmore" class="btn btn-danger">+ загрузить еще</button>
          </div>

          <?php endif; ?></main>


Function added to functions php:

function true_load_posts(){
    $args = unserialize(stripslashes($_POST['query']));
    $args['paged'] = $_POST['page'] + 1; // следующая страница
    $args['post_status'] = 'publish';
    $q = new WP_Query($args);
    if( $q->have_posts() ):
        while($q->have_posts()): $q->the_post();
            ?>
          <article class="col-md-3 col-sm-6 main-news text-left">
                            <time>
                                <?php the_time( 'j F, Y'); ?></time>
                            <div class="image-news">
                            <a href="<?php the_permalink(); ?>"> <?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'middle-thumb' ); } ?></a> </div>
                            <a href="<?php the_permalink(); ?>" class="teaser-news">
                            <?php the_title(); ?></a>
                        </article>
            <?php
        endwhile;
    endif;
    wp_reset_postdata();
    die();
}
 
 
add_action('wp_ajax_loadmore', 'true_load_posts');
add_action('wp_ajax_nopriv_loadmore', 'true_load_posts');

JS loader code:
jQuery(function($) {
  $('#true_loadmore').click(function() {
    $(this).text('Загружаю...'); // изменяем текст кнопки, вы также можете добавить прелоадер
    var data = {
      'action': 'loadmore',
      'query': true_posts,
      'page': current_page
    };
    $.ajax({
      url: ajaxurl, // обработчик
      data: data, // данные
      type: 'POST', // тип запроса
      success: function(data) {

        if (data) {
          $('#true_loadmore').text('Загрузить ещё').before(data); // вставляем новые посты
          current_page++; // увеличиваем номер страницы на единицу
          if (current_page == max_pages) $("#true_loadmore").remove(); // если последняя страница, удаляем кнопку
        } else {
          $('#true_loadmore').remove(); // если мы дошли до последней страницы постов, скроем кнопку
        }
      
      }
    });
  });

});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WP Panda, 2015-10-18
@sergey1989

The solution does not work, because you do not understand what you are doing
1. in the js script it is not clear what kind of true_posts you are passing in the query variable, but judging by the handler you are passing the main query parameters there in the form of a serialized array, this is crazy decision. it is enough to pass the pagination page number. (This does not affect the work or not of pagination, but this is not true, and this is a fucking hole through which you can get whatever you want from your database). The request must be formed entirely in the handler.
2. what does not suit you, suits if you do this

$args = unserialize(stripslashes($_POST['query']));
    $args['paged'] = $_POST['page'] + 1; // следующая страница
    $args['post_status'] = 'publish';
       $first_page_post_count = 9;
        $empty_pages_post_count = 8;

        if ($args['paged']  > 1) {
            $posts_per_page =  $empty_pages_post_count;
            if ($args['paged']  == 2) {
                $offset = $first_page_post_count;
            } else {
                $offset = $first_page_post_count + ( $empty_pages_post_count * ($args['paged']  - 2));
            }
        } else {
            $offset = 0;
            $posts_per_page = $first_page_post_count;
        }
        $args['posts_per_page'] =>$posts_per_page;
        $args['offset'] => $offset;
$q = new WP_Query($args);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question