WordPress ajax 过滤器在应该按类别过滤时返回所有帖子



这是我的代码,它应该按类别过滤,它在我单击的任何复选框上显示所有帖子,我不知道如何解决这个问题,我已经尝试了一切。

<form id="filter">
    <?php
        if( $terms = get_terms( 'category', 'orderby=name' ) ) : // to make it simple I use default categories
        foreach ( $terms as $term ) :
            echo '<input type="checkbox" name="category[]" value="' . $term->term_id . '" class="br">' . $term->name;
            echo '';
        endforeach;
        endif;
    ?>
    <div class="filter-output"></div>
</form>

这是js(在模板页面内编码(

jQuery('#filter .br').click(function(){
    // Declaratie van array
    var choices = {};
    jQuery('.contents').remove();
    jQuery('.filter-output').empty();
    jQuery('input[type=checkbox]:checked').each(function() {
        if (!choices.hasOwnProperty(this.name)) 
            choices[this.name] = [this.value];
        else 
            choices[this.name].push(this.value);
    });

    console.log(choices);
    jQuery.ajax({
        url: '<?php echo admin_url('admin-ajax.php'); ?>',
        type :'POST',
        data : {
            'action' : 'call_post', // Naam van de PHP functie
            'choices' : choices,
        },
        success: function (result) {
            jQuery('.filter-output').append(result);
            // Voor testen - Resultaat (Kan later verwijderd worden)
            //console.log(Resultaat);
            //console.log(Keuzes);
        },
        error: function(err){
            // Voor testen - Error (Kan later verwijderd worden)
            console.log(err);
            console.log(choices);
        }
    });
})

功能.php

add_action('wp_ajax_call_post', 'call_post');
add_action('wp_ajax_nopriv_call_post', 'call_post');
function call_post(){
// Verkijgen van AJAX data:
$choices = $_POST['choices'];

$meta_query = array('relation' => 'OR');
foreach($choices as $Key=>$Value){
    if(count($Value)){
        foreach ($Value as $Inkey => $Invalue) {
            $meta_query[] = array( 'key' => $Key, 'value' => $Invalue, 'compare' => '=' );
        }
    }
}
$args = array(
    'post_type' => 'post',
    'meta_query' =>$meta_query
);
$query = new WP_Query($args);
 //if( ! empty ($params['template'])) {
     ////$template = $params['template'];
     if( $query->have_posts() ) :
         while( $query->have_posts() ): $query->the_post();
             the_title();
         endwhile;
         wp_reset_query();
     else :
         wp_send_json($query->posts);
     endif;
 //}
die(); }

有人请帮忙,我从昨天开始就一直在努力完成这项工作,但根本没有运气

我已经重构了您的代码并使其工作:

模板:

<?php
/**
 *
 * Template Name: Filter Posts
 *
 */
get_header();
$args = array(
    'post_type'      => 'post',
    'posts_per_page' => -1,
);
$tax_query  = array();
$categories = get_terms( 'category', 'orderby=name' );
if ( ! empty( $choices = get_request_param( 'choices' ) ) ) {
    $term_ids = explode(',', $choices);
    $tax_query[] = array(
        'taxonomy' => 'category',
        'field'    => 'term_id',
        'terms'    => $term_ids
    );
    $args['tax_query'] = $tax_query;
}
$query = new WP_Query( $args );
if ( ! empty( $categories ) ) : ?>
    <form action="?" method="post" class="form-filter">
        <?php foreach ( $categories as $category ) : ?>
            <div class="checkbox">
                <input type="checkbox" name="category[]" data-category="<?php echo esc_attr( $category->term_id ); ?>" id="<?php echo esc_attr( $category->slug ); ?>">
                <label for="<?php echo esc_attr( $category->slug ); ?>">
                    <?php echo esc_html( $category->name ); ?>
                </label>
            </div><!-- /.checkbox -->
        <?php endforeach; ?>
    </form><!-- /.form-filter -->
<?php endif; ?>
<div class="filter-output">
    <ul>
        <?php while ( $query->have_posts() ) : $query->the_post(); ?>
            <li>
                <?php the_title(); ?>
            </li>
        <?php endwhile; ?>
    </ul>
</div><!-- /.filter-output -->
<?php
wp_reset_postdata();
get_footer();

Javascript:

;(function(window, document, $) {
    var $win = $(window);
    var $doc = $(document);
    $doc.on('change', '.form-filter', function() {
        var choices = '';
        $('.form-filter input:checked').each(function() {
            if ( choices === '' ) {
                choices += $(this).data('category');
            } else {
                choices += ',' + $(this).data('category');
            }
        });
        $.ajax({
            url: window.location.href,
            type: 'GET',
            data: {
                'choices' : choices,
            },
            success: function(response) {
                var newPosts = $(response).filter('.filter-output').html();
                $('.filter-output').html(newPosts);
            }
        });
    });
})(window, document, window.jQuery);

函数.php

function get_request_param( $key = '' ) {
    $value = false;
    if ( ! $key ) {
        return $value;
    }
    if ( isset( $_POST[$key] ) ) {
        $value = $_POST[$key];
    } elseif ( isset( $_GET[$key] ) ) {
        $value = $_GET[$key];
    }
    return $value;
}

几点注意事项:

1( 使用 jquery 更改事件,而不是单击过滤器表单。

2(在这种情况下不需要WP AJAX。您可以简单地向同一页面发出GET请求,并在需要时更改HTML。

3( 使用 GET 方法代替 POST

最新更新