最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Ajax filter button display all posts

programmeradmin1浏览0评论

I created a loop for my Custom Posts Type workshop with two custom taxonomies group and teacher on the same page. The Ajax filter works perfectly thanks to the solution provided here. The user can select one taxonomy or both to display the posts.

Each links of the filter works with a <input type="radio"...>, for both taxonomies lists. What I'm trying to achieve is to create a button .filter-reset which resets all the radio inputs and displays all the posts of my Custom Posts Type.

The issue is when I click the button, it returns "No posts found".

Here is the PHP code for the filter in the frontend:

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

   if( $terms = get_terms( 'group', 'orderby=name&exclude=-1' ) ) :
    echo '<div class="filter-tax filter--group">';
    foreach ( $terms as $term ) :
      echo '<input class="btn-radio" type="radio" name="categoryfilter1" value="' . $term->term_id . '"><label>' . $term->name . '</label>';
    endforeach;
    echo '</div>';
   endif;

   if( $terms = get_terms( 'teacher', 'orderby=name&exclude=-1' ) ) :
     echo '<div class="filter-tax filter--teacher">';
     foreach ( $terms as $term ) :
       echo '<input class="btn-radio" type="radio" name="categoryfilter2" value="' . $term->term_id . '"><label>' . $term->name . '</label>';
     endforeach;
     echo '</div>';
    endif;

    ?>

    <a href="#" class="filter-reset">View all</a>

    <input type="hidden" name="action" value="myfilter">
  </div>
</form>

The PHP code for the AJAX filter in my functions.php:

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

function mysite_filter_function(){

   $args = array(
        'orderby' => 'date',
        'posts_per_page' => -1
   );

   if (isset($_POST['categoryfilter1']) && isset($_POST['categoryfilter2'])) {

        $args['tax_query'] = array(
            'relation' => 'AND',
            array(
                'taxonomy' => 'group',
                'field' => 'id',
                'terms' => $_POST['categoryfilter1']
            ),
            array(
                'taxonomy' => 'teacher',
                'field' => 'id',
                'terms' => $_POST['categoryfilter2']
            ),
        );

   } elseif (isset($_POST['categoryfilter1']) && !isset($_POST['categoryfilter2'])) {

        $args['tax_query'] = array(
        array(
        'taxonomy' => 'group',
        'field' => 'id',
        'terms' => $_POST['categoryfilter1']
        )
        );

   } elseif (!isset($_POST['categoryfilter1']) && isset($_POST['categoryfilter2'])) {

        $args['tax_query'] = array(
        array(
        'taxonomy' => 'teacher',
        'field' => 'id',
        'terms' => $_POST['categoryfilter2']
        )
        );

   }

    $query = new WP_Query( $args );

    if( $query->have_posts() ) :
        while( $query->have_posts() ): $query->the_post();
            get_template_part( 'template-parts/content-archive' );
        endwhile;
        wp_reset_postdata();
    else :
        echo 'No posts found';
    endif;

    die();
}

The JS code:

$('#filter').change(function(){
    var filter = $('#filter');
    $.ajax({
        url:filter.attr('action'),
        data:filter.serialize(),
        type:filter.attr('method'),
        beforeSend:function(xhr){
            //filter.find('button').text('Processing...');
        },
        success:function(data){
            //filter.find('button').text('Filter');
            $('.loop-archive').html(data);
        }
    });
    return false;
});

$(".filter-reset").click(function() {
    document.getElementById('filter').reset();
    $('.loop-archive-workshop').append();

    var filter = $('#filter');

    $.ajax({
        url:filter.attr('action'),
        type:filter.attr('method'),
        data:filter.serialize(),
        success:function(data){
            $('.loop-archive').html(data);
        }
    });
    return false;
});

Thank you.

EDIT

Here is the log.txt when I click the reset button:

Array
(
    [action] => myfilter
)

I created a loop for my Custom Posts Type workshop with two custom taxonomies group and teacher on the same page. The Ajax filter works perfectly thanks to the solution provided here. The user can select one taxonomy or both to display the posts.

Each links of the filter works with a <input type="radio"...>, for both taxonomies lists. What I'm trying to achieve is to create a button .filter-reset which resets all the radio inputs and displays all the posts of my Custom Posts Type.

The issue is when I click the button, it returns "No posts found".

Here is the PHP code for the filter in the frontend:

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

   if( $terms = get_terms( 'group', 'orderby=name&exclude=-1' ) ) :
    echo '<div class="filter-tax filter--group">';
    foreach ( $terms as $term ) :
      echo '<input class="btn-radio" type="radio" name="categoryfilter1" value="' . $term->term_id . '"><label>' . $term->name . '</label>';
    endforeach;
    echo '</div>';
   endif;

   if( $terms = get_terms( 'teacher', 'orderby=name&exclude=-1' ) ) :
     echo '<div class="filter-tax filter--teacher">';
     foreach ( $terms as $term ) :
       echo '<input class="btn-radio" type="radio" name="categoryfilter2" value="' . $term->term_id . '"><label>' . $term->name . '</label>';
     endforeach;
     echo '</div>';
    endif;

    ?>

    <a href="#" class="filter-reset">View all</a>

    <input type="hidden" name="action" value="myfilter">
  </div>
</form>

The PHP code for the AJAX filter in my functions.php:

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

function mysite_filter_function(){

   $args = array(
        'orderby' => 'date',
        'posts_per_page' => -1
   );

   if (isset($_POST['categoryfilter1']) && isset($_POST['categoryfilter2'])) {

        $args['tax_query'] = array(
            'relation' => 'AND',
            array(
                'taxonomy' => 'group',
                'field' => 'id',
                'terms' => $_POST['categoryfilter1']
            ),
            array(
                'taxonomy' => 'teacher',
                'field' => 'id',
                'terms' => $_POST['categoryfilter2']
            ),
        );

   } elseif (isset($_POST['categoryfilter1']) && !isset($_POST['categoryfilter2'])) {

        $args['tax_query'] = array(
        array(
        'taxonomy' => 'group',
        'field' => 'id',
        'terms' => $_POST['categoryfilter1']
        )
        );

   } elseif (!isset($_POST['categoryfilter1']) && isset($_POST['categoryfilter2'])) {

        $args['tax_query'] = array(
        array(
        'taxonomy' => 'teacher',
        'field' => 'id',
        'terms' => $_POST['categoryfilter2']
        )
        );

   }

    $query = new WP_Query( $args );

    if( $query->have_posts() ) :
        while( $query->have_posts() ): $query->the_post();
            get_template_part( 'template-parts/content-archive' );
        endwhile;
        wp_reset_postdata();
    else :
        echo 'No posts found';
    endif;

    die();
}

The JS code:

$('#filter').change(function(){
    var filter = $('#filter');
    $.ajax({
        url:filter.attr('action'),
        data:filter.serialize(),
        type:filter.attr('method'),
        beforeSend:function(xhr){
            //filter.find('button').text('Processing...');
        },
        success:function(data){
            //filter.find('button').text('Filter');
            $('.loop-archive').html(data);
        }
    });
    return false;
});

$(".filter-reset").click(function() {
    document.getElementById('filter').reset();
    $('.loop-archive-workshop').append();

    var filter = $('#filter');

    $.ajax({
        url:filter.attr('action'),
        type:filter.attr('method'),
        data:filter.serialize(),
        success:function(data){
            $('.loop-archive').html(data);
        }
    });
    return false;
});

Thank you.

EDIT

Here is the log.txt when I click the reset button:

Array
(
    [action] => myfilter
)
Share Improve this question edited Feb 19, 2021 at 17:07 Mathieu Préaud asked Feb 19, 2021 at 15:10 Mathieu PréaudMathieu Préaud 2035 silver badges18 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

Going by what @JacobPeattie said, that they are still set but empty you need to change the conditional login to check for empty.

In our previous discussion I wrote this conditions

if ((isset($_POST['categoryfilter1']) && !empty($_POST['categoryfilter1'])) && (isset($_POST['categoryfilter2']) && !empty($_POST['categoryfilter2']))) {
    // both properties are set and have value (not empty)
} elseif ((isset($_POST['categoryfilter1']) && !empty($_POST['categoryfilter1'])) && (!isset($_POST['categoryfilter2']) || empty($_POST['categoryfilter2']))) {
    // only categoryfilter1 is set and has value and categoryfilter2 is either not set or set but has no value
} elseif ((!isset($_POST['categoryfilter1']) || empty($_POST['categoryfilter1'])) && (isset($_POST['categoryfilter2']) && !empty($_POST['categoryfilter2']))) {
    // only categoryfilter2 is set and has value and categoryfilter1 is either not set or set but has no value
}

Try using it and see if it helps

EDIT

I dont know what post type you want to get but try adding it to the $args as well.

So you initial $args will look like this

$args = array(
    'post_type' => 'post',
    // 'post_status' => 'publish', // this is optional, this will get only published posts
    'orderby' => 'date',
    'posts_per_page' => -1
);

I think that this creates the problem

The issue is using isset() for the conditions:

isset($_POST['categoryfilter1']) && isset($_POST['categoryfilter2'])

Because those inputs are still part of the form their post variables will still be set, they'll just be empty. Using !empty() and empty() would be the way to go:

if (isset($_POST['categoryfilter1']) && isset($_POST['categoryfilter2'])) {
    // etc.
} elseif (!empty($_POST['categoryfilter1']) && empty($_POST['categoryfilter2'])) {
    // etc.
} elseif (empty($_POST['categoryfilter1']) && !empty($_POST['categoryfilter2'])) {
    // etc.
}
发布评论

评论列表(0)

  1. 暂无评论