A
A
Alexey102020-05-24 23:36:41
WordPress
Alexey10, 2020-05-24 23:36:41

How to add show more button to wp post filter?

Hello everyone)
I made a button on Ajax to show more for posts and made a filter by date for the same posts. But unfortunately they conflict with each other. For example, I load several posts using the button, and after that I click on the filter by date radio button, and it filters only the first 12 posts for me (which were originally). And it crashes everything. How to combine these two codes so that they do not interfere with each other? (Perhaps someone has similar solutions? Or an article on the Internet so that both the post filter and the show button still work).

archive.php

<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="post-date-filter">
  <ul class="tabs-list-articles flex">
    <li>
      <label class="label_filter_block">
        <input class="filter_radio filter_radio-js" type="radio" name="date" value="DESC" checked  />
        <span>Сначала новые</span>
      </label>
    </li>
    <li>
      <label class="label_filter_block">
        <input class="filter_radio filter_radio-js" type="radio" name="date" value="ASC" />
        <span>Сначала старые</span>
      </label>
    </li>
  </ul>
  <input type="hidden" name="action" value="customfilter">
</form>

<div class="item-tabs-content-article parent-post-js">
  <div class="items-article">

    

    <div class="row no-padding-20 filter-post-js">
      <?php 

        $params = array(
          'posts_per_page' => 12,
        );
        query_posts($params);
           
        $wp_query->is_archive = true;
        $wp_query->is_home = false;
      ?>
      <?php

        while ( have_posts() ) :
          the_post();
          ?>
          <?php get_template_part( 'template-parts/content', 'post_news' ); ?>
      <?php
        endwhile;

      ?>

    </div>
  </div>

    <?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="btn-main-article">
      <a class="button button-loading-js" href="#">Показать еще</a>
    </div>
  <?php endif; ?>


  
</div>


function.php file
// кнопка подгрузки постов
function true_load_posts(){
 
  $current_page = (get_query_var('paged')) ? get_query_var('paged') : 1;
  $params = array(
    'posts_per_page' => 12,
    'orderby' => 'date',
    	'order' => $_POST['date']
  );
  query_posts($params);
  $params = unserialize( stripslashes( $_POST['query'] ) );
  $params['paged'] = $_POST['page'] + 1; // следующая страница
  $params['post_status'] = 'publish';

  if( have_posts() ) :
    while( have_posts() ): the_post();
 
      get_template_part( 'template-parts/content', 'post_news' );
 
    endwhile;
 
  endif;
  die();
}
// фильтр подгрузки постов
function posts_filters(){

  $params = array(
    'posts_per_page' => 12,
    'orderby' => 'date',
    	'order' => $_POST['date']
  );
  query_posts($params);

  while ( have_posts() ) :
    the_post();
    
    get_template_part( 'template-parts/content', 'post_news' ); 

  endwhile;


   die();
}
add_action('wp_ajax_customfilter', 'posts_filters');
add_action('wp_ajax_nopriv_customfilter', 'posts_filters');

add_action('wp_ajax_loadmore', 'true_load_posts');
add_action('wp_ajax_nopriv_loadmore', 'true_load_posts');


ajax
// подгрузка постов через аякс
$('.button-loading-js').on('click', function(e){
  e.preventDefault();
  $(this).text('Загрузка...'); // изменяем текст кнопки, вы также можете добавить прелоадер
  var data = {
    'action': 'loadmore',
    'query': true_posts,
    'page' : current_page
  };
  $.ajax({
    url:ajaxurl, // обработчик
    data:data, // данные
    type:'POST', // тип запроса
    success:function(data){
      if( data ) { 
        $('.button-loading-js').text('Показать еще').parents('.parent-post-js').find('.row .post-js').last().after(data); // вставляем новые посты
        current_page++; // увеличиваем номер страницы на единицу
        if (current_page == max_pages) $('.button-loading-js').parent().remove(); // если последняя страница, удаляем кнопку
      } else {
        $('.button-loading-js').parent().remove(); // если мы дошли до последней страницы постов, скроем кнопку
      }
    }
  });

  $.ajax({
     url:filter.attr('action'),
     data:filter.serialize(), 
     type:filter.attr('method'),
     success:function(data){ 
       $('.filter-post-js').html(data); 
    }
  });

});

// фильтр постов через аякс
$('.filter_radio-js').on('change', function() {
var filter = $('#post-date-filter');
$.ajax({
   url:filter.attr('action'),
   data:filter.serialize(), 
   type:filter.attr('method'),
   success:function(data){ 
     $('.filter-post-js').html(data); 
  }
});

return false;
});

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