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

时间:2019-02-10 00:01:38

标签: php jquery ajax wordpress

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

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

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

任何人都请帮忙,从昨天开始,我一直在努力进行这项工作,而且一无所获

1 个答案:

答案 0 :(得分:0)

我已经重构了您的代码并使之生效:

模板:

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

functions.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 change事件,而不是单击以获取过滤器表单。

2)在这种情况下,不需要WP AJAX。您只需向同一页面发出GET请求,然后在需要的地方更改HTML。

3)使用GET方法而不是POST