Search code examples
phpwordpressfiltertaxonomy

Ajax filter for wordpress


after a lot of research i came across this: https://rudrastyh.com/wordpress/ajax-post-filters.html

But I can only get it to work when there are two options selected.

I'll give you some context: I have a CPT named 'Contratistas' that has two custom taxonomies 'especialidad' and 'industria', they both have two terms each 'especialidad' -> 'tecnologia' and 'auditoria'; 'industria' -> 'cultivo' and 'depocito'

here is my function:

function misha_filter_function(){
    $args = array(
        'orderby' => 'date', // we will sort posts by date
        'order' => $_POST['date'], // ASC or DESC
        'post_per_page' => -1,
        'post_type' => 'contratista'
    );
    // for taxonomies / categories
    if( isset( $_POST['filtroEspecialidad'] ) && isset ($_POST['filtroIndustria'])  ) {
        $args['tax_query'][] = array(
         //'relation' => 'AND',
            array(
                'taxonomy' => 'especialidad',
                'field' => 'id',
                'terms' => $_POST['filtroEspecialidad']
            ),
            array(
                'taxonomy' => 'industria',
                'field' => 'id',
                'terms' => $_POST['filtroIndustria']
            ),
        );
    
    } elseif( !isset($_POST['filtroEspecialidad'] ) && isset($_POST['filtroIndustria'])  ) {
        $args['tax_query'][] = array(
            'taxonomy' => 'industria',
            'field' => 'id',
            'terms' => $_POST['filtroIndustria']
        );
    
    } elseif( isset( $_POST['filtroEspecialidad'] ) && !isset($_POST['filtroIndustria'])  ) {
        $args['tax_query'][] = array(
            'taxonomy' => 'especialidad',
            'field' => 'id',
            'terms' => $_POST['filtroEspecialidad']
        );
    }

It works if you select something from both taxonomies, but when one is empty it says 'there are no post'

as a bonus I will like to show all the post before filtering.

I hope somebody can help me! Thanks! I'm fairly new to Wordpress

EDIT! Here is my js and my form, i'm at a loss here I can't figure out what's wrong :(

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('.filtrar').text('Procesando...'); // changing the button label
            },
            success:function(data){
                filter.find('.filtrar').text('Filtrar'); // changing the button label back
                $('#response').html(data); // insert data
            }
        });
        return false;
    });

my php file:

<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
                    <div class="titulo mb-3">
                        <h3>Especialidad</h3>
                    </div>
                    <?php
                        if( $terms = get_terms( array( 'taxonomy' => 'especialidad', 'orderby' => 'name' ) ) ) : 
                 
                            echo '<select name="filtroEspecialidad"><option value="">Seleccione una especialidad...</option>';
                            foreach ( $terms as $term ) :
                                echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as the value of an option
                            endforeach;
                            echo '</select>';
                        endif;
                        
                    ?>
                    <div class="titulo my-3">
                        <h3>Industrias</h3>
                    </div>
                    <?php   
                        if( $terms = get_terms( array( 'taxonomy' => 'industria', 'orderby' => 'name' ) ) ) : 
                 
                            echo '<select name="filtroIndustria"><option value="">Seleccione una industria...</option>';
                            foreach ( $terms as $term ) :
                                echo '<option  value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as the value of an option
                            endforeach;
                            echo '</select>';
                        endif;
                    ?>  
                    <button class="my-3 filtrar">Filtrar</button>
                    <a href="" id="clear">Clear</a>
                    <input type="hidden" name="action" value="myfilter">
                </form>


Solution

  • You may want to give the Taxonomy Parameters of WP_Query() another glance. Unfortunately, WordPress is a little loose with it's id parameter names contextually. I'm not entirely sure your initial "both" is working like you intend either, because 'field' => 'id' is actually invalid.

    From the docs:

    field (string) – Select taxonomy term by. Possible values are term_id, name, slug or term_taxonomy_id. Default value is term_id.

    id isn't actually a valid option. If you're just using the term_id, you should be able to omit that. You can also just programatically add the tax_query array arguments based on if that filter is set, instead of checking for "both set, this set/that unset, this unset, that set", something like this perhaps?

    function misha_filter_function(){
        $args = array(
            'orderby'       => 'date', // we will sort posts by date
            'order'         => $_POST['date'], // ASC or DESC
            'post_per_page' => -1,
            'post_type'     => 'contratista'
        );
    
        if( isset($_POST['filtroEspecialidad']) || isset($_POST['filtroIndustria']) ){
            $args['tax_query'] = array();
            
            if( isset($_POST['filtroEspecialidad']) ){
                $args['tax_query'][] = array(
                    'taxonomy' => 'especialidad',
                    'terms'    => $_POST['filtroEspecialidad']
                );
            }
            
            if( isset($_POST['filtroIndustria']) ){
                $args['tax_query'][] = array(
                    'taxonomy' => 'industria',
                    'terms'    => $_POST['filtroIndustria']
                );
            }
    
            if( count($args['tax_query']) > 1 ){
                $args['tax_query']['relation'] = 'AND';
            }
        }
    
        // Run WP_Query with new $args, etc.
    }
    

    I'm not sure if the $_POST values are arrays or single numbers, but you may want to validate those with array_map and/or absint if you're using user-supplied input, but if they're just IDs, the above should work for now.