Ajax фильтр сообщений по категориям - PullRequest
0 голосов
/ 15 октября 2019

У меня есть 2 родительские категории (country, fruit), и я получаю их детей. Теперь я хочу отфильтровать их.

Я подписался на этот пост: https://rudrastyh.com/wordpress/ajax-post-filters.html

enter image description here

Но когда я нажимаю Apple, я хочу показать толькоЯблоки Netherlands, а не Spain или любой другой страны.

Это мои checkboxes:

<h3>Country</h3>
        <?php
            $args = array('child_of' => 89);
            $categories = get_categories( $args );
            foreach($categories as $category) { 
                echo '<input type="checkbox" name="categoryfilter[]" 
value="'.$category->cat_ID.'"> '.$category->name.'<br />';
            }
        ?>

        <h3>Fruit</h3>
        <?php
            $args = array('child_of' => 84);
            $categories = get_categories( $args );
            foreach($categories as $category) { 
                echo '<input type="checkbox" name="categoryfilter[]" 
value="'.$category->cat_ID.'"> '.$category->name.'<br />';
            }
        ?>

Это моя функция фильтрации:

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
    'posts_per_page' => -1 // show all posts.
);

// category filter function
if( isset( $_POST['categoryfilter_country'] ) && isset 
($_POST['categoryfilter_fruit']) )
    $args['tax_query'] = array( 'relation' => 'AND' );
    $args['tax_query'] = array(
        array(
            'taxonomy' => 'category',
            'field' => 'id',
            'terms' => $_POST['categoryfilter_country']
        ),
        array(
            'taxonomy' => 'category',
            'field' => 'id',
            'terms' => $_POST['categoryfilter_fruit']
        )
    );

$query = new WP_Query( $args );

// query here ...

die();
}

А это скрипт фильтра:

jQuery(function($){
            $('#filter').change(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('Apply filter'); // 
changing the button label back
                        $('#response').html(data); // insert data
                    }
                });
                return false;
            });
        });

1 Ответ

0 голосов
/ 15 октября 2019

Я понял это. Вот финальный скрипт для 2 групп флажков («Vertragsart» + «Zeitmodell»). Когда вы ставите флажок в одной группе (например, «Zeitmodell»), он фильтрует сообщения - когда вы дополнительно ставите флажок в другой группе (например, «Vertragsart»), сценарий проверяет, подходят ли оба элемента вместе (в терминах «общий доступ к сообщениям»). той же категории ").

Функция:

add_action('wp_ajax_myfilter', 'misha_filter_function');
add_action('wp_ajax_nopriv_myfilter', 'misha_filter_function');

function misha_filter_function(){
$args = array(
    'orderby' => 'date',
    'order' => $_POST['date'],
    'posts_per_page' => -1
);

// for taxonomies / categories
if( isset( $_POST['vertragsart'] ) && isset ($_POST['zeitmodell'])  ) {
    $args['tax_query'][] = array(
    // 'relation' => 'AND',

        array(
            'taxonomy' => 'category',
            'field' => 'id',
            'terms' => $_POST['vertragsart']
        ),
        array(
            'taxonomy' => 'category',
            'field' => 'id',
            'terms' => $_POST['zeitmodell']
        ),
    );

} elseif( !isset( $_POST['vertragsart'] ) && isset ($_POST['zeitmodell'])  ) {
    $args['tax_query'][] = array(
        'taxonomy' => 'category',
        'field' => 'id',
        'terms' => $_POST['zeitmodell']
    );

} elseif( isset( $_POST['vertragsart'] ) && !isset ($_POST['zeitmodell'])  ) {
    $args['tax_query'][] = array(
        'taxonomy' => 'category',
        'field' => 'id',
        'terms' => $_POST['vertragsart']
    );
}

$query = new WP_Query( $args );

if( $query->have_posts() ) :
    while( $query->have_posts() ): $query->the_post();
        echo '<article>';
        echo '<h4>' . $query->post->post_title . '</h4>';
        get_template_part('/template_parts/categories_jobs');
        echo '</article>';
    endwhile;
    wp_reset_postdata();
else :
    echo 'Im Moment keine Stellenangebote.';
endif;
die();
}

Форма:

<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">

        <h3>Vetragsart</h3>
        <?php
            $args = array('child_of' => 92);
            $categories = get_categories( $args );
            foreach($categories as $category) { 
                echo '<input type="checkbox" name="vertragsart[]" value="'.$category->cat_ID.'"> '.$category->name.'<br />';
            }
        ?>

        <br />
        <h3>Zeitmodell</h3>
        <?php
            $args = array('child_of' => 93);
            $categories = get_categories( $args );
            foreach($categories as $category) { 
                echo '<input type="checkbox" name="zeitmodell[]" value="'.$category->cat_ID.'"> '.$category->name.'<br />';
            }
        ?>

        <!-- <button>Apply filter</button> -->
        <input type="hidden" name="action" value="myfilter">
    </form>

Сценарий jQuery (ничего не изменилось):

jQuery(function($){
            $('#filter').change(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('Apply filter'); // changing the button label back
                        $('#response').html(data); // insert data
                    }
                });
                return false;
            });
        });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...