S
S
sergey19892015-10-15 18:37:07
CMS
sergey1989, 2015-10-15 18:37:07

How to set a certain number of posts per page in WordPress pagination?

Good day. The task was to make AJAX loading posts in WordPress, but the problem is that 9 posts should be displayed on the first page, and when you click on the "load more" button, 8 posts should be loaded. But the load script works with WP's pagination, which has an equal number of posts on each page. What is the best way to get out of this situation and is it even possible? I am attaching the ajax loading code:

Displaying records in index.php

<main class="row">
          <?php 
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
   'posts_per_page' =>
          '9',
);
$wp_query = new WP_Query( $args );
?>
          <?php $loop = 0; ?>
          <?php while ( $wp_query->
          have_posts() ) : $wp_query->the_post();?>
          <?php $loop++; ?>
          <?php if( $loop == 1) {?>
          <article class="col-md-8 col-sm-8 main-news">
            <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( 'large-thumb' ); } ?></a>
            </div>
            <a href="<?php the_permalink(); ?>
              " class="teaser-news">
              <?php the_title(); ?></a>
          </article>

          <?php } elseif( $loop == 2 ) { ?>
          <article class="col-md-4 col-sm-4 main-news">
            <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( 'big-thumb' ); } ?></a>
            </div>
            <a href="<?php the_permalink(); ?>
              " class="teaser-news">
              <?php the_title(); ?></a>
          </article>
          <?php } elseif( $loop >
          2 && $loop
          <= 5 ){ ?>
            <article class="col-md-4 col-sm-6 main-news">
              <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 } elseif( $loop >
            5 ) { ?>
            <article class="col-md-3 col-sm-6 main-news">
              <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 } ?>
            <?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="row">
              <div class="col-md-12 text-center">
                <button type="button" id="true_loadmore" class="btn btn-danger">+ загрузить еще</button>
              </div>
            </div>

            <?php endif; ?></main>


PHP handler code in 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 loading 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(); // если мы дошли до последней страницы постов, скроем кнопку
        }
        $(".image-news")
    .mouseenter(function() {
      $(this).next().css('background', '#B00402');
    })
    .mouseleave(function() {
      $(this).next().css('background', '#3A3939');
    });
      }
    });
  });

});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WP Panda, 2015-10-16
@wppanda5

Like this
to make a Wordpress post page with pagination display 8 posts on the first page and 16 on the rest?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question