Фильтрация по нескольким таксономиям и пагинация?

Сейчас у меня выводятся кастомные программы в functions следующим образом:
add_action('wp_ajax_myfilter', 'misha_filter_function'); // wp_ajax_{ACTION HERE} 
add_action('wp_ajax_nopriv_myfilter', 'misha_filter_function');
 
function misha_filter_function(){
	$args = array(
		'orderby' => 'date', // we will sort posts by date
		'order'	=> $_POST['date'] // ASC or DESC
	);
 
	// for taxonomies / categories
	if( isset( $_POST['level'] ) )
		$args['tax_query'] = array(
			array(
				'taxonomy' => 'level',
				'field' => 'id',
				'terms' => $_POST['level']
			)
		);
		
	
 
	// create $args['meta_query'] array if one of the following fields is filled
	if( isset( $_POST['price_min'] ) && $_POST['price_min'] || isset( $_POST['price_max'] ) && $_POST['price_max'] || isset( $_POST['featured_image'] ) && $_POST['featured_image'] == 'on' )
		$args['meta_query'] = array( 'relation'=>'AND' ); // AND means that all conditions of meta_query should be true
 
	// if both minimum price and maximum price are specified we will use BETWEEN comparison
	if( isset( $_POST['price_min'] ) && $_POST['price_min'] && isset( $_POST['price_max'] ) && $_POST['price_max'] ) {
		$args['meta_query'][] = array(
			'key' => '_price',
			'value' => array( $_POST['price_min'], $_POST['price_max'] ),
			'type' => 'numeric',
			'compare' => 'between'
		);
	} else {
		// if only min price is set
		if( isset( $_POST['price_min'] ) && $_POST['price_min'] )
			$args['meta_query'][] = array(
				'key' => '_price',
				'value' => $_POST['price_min'],
				'type' => 'numeric',
				'compare' => '>'
			);
 
		// if only max price is set
		if( isset( $_POST['price_max'] ) && $_POST['price_max'] )
			$args['meta_query'][] = array(
				'key' => '_price',
				'value' => $_POST['price_max'],
				'type' => 'numeric',
				'compare' => '<'
			);
	}
 
 
	// if post thumbnail is set
	if( isset( $_POST['featured_image'] ) && $_POST['featured_image'] == 'on' )
		$args['meta_query'][] = array(
			'key' => '_thumbnail_id',
			'compare' => 'EXISTS'
		);
	// if you want to use multiple checkboxed, just duplicate the above 5 lines for each checkbox
 
	$query = new WP_Query( $args );
 
	if( $query->have_posts() ) :
		while( $query->have_posts() ): $query->the_post(); ?>
			<div class="program-main">
				// Какой-то контент
			</div>
			<?php
		endwhile;
		wp_reset_postdata();
	else : ?>
		<div class="card-no-result">
			<h2>Нет подходящей программы?</h2>
			<p>Напишите нам об этом и мы придумаем для вас индивидуальное  решение.</p>
			<a class="btn popup-call" href="#modal">Получить решение</a>
		</div> 
		<?php
	endif;
 
 
	die();
}

Форма (не вся, потому что займёт много места, там повторяются таксономии) с помощью которой мы выбираем нужную таксономию и после нажатия выполняется код в functions:
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
	<div class="simple-filter_item button-group filters">
		<p class="rus">Уровень подготовки</p>
		<?php
		$categories = get_terms('level', 'orderby=name&hide_empty=0');
		if($categories){
			echo '<select name="level" id="level1"><option value="card-item">Любой</option>';
			foreach ($categories as $cat){
				echo "<option value='{$cat->term_id}'>{$cat->name}</option>";
			}
			echo '</select>';
		}
		?>
	</div>
	<div class="simple-filter_item">
		<p>Направление образования</p>
		<?php
			$categories = get_terms('direction', 'orderby=name&hide_empty=0');
			if($categories){
				echo '<select name="direction" id="direction1"><option value="card-item">Любое</option>';
				foreach ($categories as $cat){
					echo "<option value='direction-{$cat->term_id}'>{$cat->name}</option>";
				}
				echo '</select>';
			}
		?>
	</div>
	<div class="filter-button filter-disactive">
		<div class="simple-btn">
			<button class="btn_access func-during">Подобрать</button>
			<input type="hidden" name="action" value="myfilter">
		</div>
	</div>
</form>

Ну и скрипт с помощью которого я могу указать, что после нажатия на кнопку форма должна обрабатываться и выводится в необходимом div с id = card-wrapper-first:
jQuery(function ($) {
  $("#filter").submit(function () {
    var filter = $("#filter");
    $.ajax({
      url: filter.attr("action"),
      data: filter.serialize(), // form data
      type: filter.attr("method"), // POST
      beforeSend: function (xhr) {
        filter.find("button").text("Processing..."); // changing the button label
      },
      success: function (data) {
        filter.find("button").text("Подобрать"); // changing the button label back
        $("#card-wrapper-first").html(data); // insert data
      },
    });
    return false;
  });
});

Подведём итоги из всего: как можно переделать функцию из functions.php, чтобы фильтровались программы не с помощью одной таксономии (уровень подготовки), а с учётом и других тоже (указал здесь только 2, но на деле их 5). И как мне сделать пагинацию, чтобы они выводились не все разом, потому что их может быть более 200, а только по 30 на одной странице

Заранее огромное спасибо за ваше терпение и помощь!
  • Вопрос задан
  • 535 просмотров
Пригласить эксперта
Ответы на вопрос 2
cesnokov
@cesnokov
<head>&nbsp;</head>
if( isset($_POST['level']) && isset($_POST['direction']) ) {
    $args['tax_query'][] = array(
        'relation' => 'AND'
    );
}

if( isset($_POST['level']) ) {
    $args['tax_query'][] = array(
        array(
            'taxonomy' => 'level',
            'field' => 'id',
            'terms' => $_POST['level']
        )
    );
}

if( isset($_POST['direction']) ) {
    $args['tax_query'][] = array(
        array(
            'taxonomy' => 'direction',
            'field' => 'id',
            'terms' => $_POST['direction']
        )
    );
}


Пагинация:
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
    'orderby' => 'date', // we will sort posts by date
    'order' => $_POST['date'], // ASC or DESC
    'posts_per_page' => 30,
    'paged' => $paged
);
Ответ написан
Комментировать
@IvanZhukov
plugin-wp.ru - премиум плагины для Wordpress
Чтобы фильтрация проходила по нескольким таксономиям сразу, можно применить код из документации:
https://developer.wordpress.org/reference/classes/...
Раздел - "Multiple Taxonomy Handling"

В данном конкретном примере для двух таксономий рабочий код будет выглядеть вот так:

$args = array(
		'post_type' => 'your_post_type',
		'tax_query' => array(
			'relation' => 'AND',
			array(
				'taxonomy' => 'level',
				'field'    => 'id',
				'terms'    => $_POST[ 'level' ],
				'operator' => 'AND',
			),
			array(
				'taxonomy' => 'direction',
				'field'    => 'id',
				'terms'    => $_POST[ 'direction' ],
				'operator' => 'AND',
			),
		),
	);
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы