mardi 15 octobre 2019

Ajax filter posts by Category

I have 2 parent categories ("country", "fruit") and get the children of them. Now I want to filter them.

I followed this post: https://rudrastyh.com/wordpress/ajax-post-filters.html

enter image description here

But when I click "Apple" I want to show only the Apples from "Netherlands" and not the ones from "Spain" or any other country.

This are my 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 />';
            }
        ?>

This is my filter function:

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();
}

And this is the filter script:

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;
            });
        });



Aucun commentaire:

Enregistrer un commentaire