0

Сейчас у меня выводятся кастомные программы в 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="card-item">
                <!-- какой-то контент -->
            </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;
});

});

Вывод пагинации идёт сразу после вывода всех программ:

<?php  $query = new WP_Query( 'post_type=program-card' ); ?>
<?php while ( $query->have_posts()):$query->the_post(); ?>
   <div class="card-item">
       <!-- Какой-то контент... -->
   </div>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php kama_pagenavi($before = '', $after = '', $echo = true, $args = array(), 
$wp_query = $query); ?>

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

Заранее огромное спасибо за ваше терпение и помощь!

2
  • Где вывод пагинации то?)
    – user243545
    20 июл 2020 в 9:22
  • @WPPunk Извиняюсь, был уверен, что добавил, но не перечитал всё. Дополнил ответ)
    – Рома
    20 июл 2020 в 10:37

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Посмотрите другие вопросы с метками или задайте свой вопрос.