0

I am trying to create a post filter for my website.

jQuery(document).ready(function($) {
    $("input[id='brand']").click(function() {
        var key;
        var value;
        var checked;
        var check = $(this).prop("checked");
        if (check) {
            key = $(this).attr('id');
            value = $(this).val();
            checked = 'true';
        } else {
            checked = 'false';
        }
        var ajax_url = 'http://localhost/wordpress/wp-admin/admin-ajax.php';
        var data = {
            'action': 'filter_posts_by_meta',
            'checked': checked,
            'key': key,
            'value': value,
        };
        $.ajax({
            method: "POST",
            url: ajax_url,
            data: data,
            success: function(result) {
                jQuery('#sortid').html(result);
            },
            error: function(xhr, status, error) {
                // console.log(error);
            }
        });
    });
});

the php script:

function ajax_filter_posts_by_meta () {
    global $wp_query, $wp_the_query;

    //$compare= isset($_POST['compare']) ? $_POST['compare'] : '';
    $key = isset($_POST['key']) ? $_POST['key'] : '';
    $value = isset($_POST['value']) ? $_POST['value'] : '';
    $checked = isset ($_POST['checked']) ? $_POST['checked'] : die();

    //if ($checked != 'true'){}

    $filterargs=   array(array($qv) , array(
        array(
            'key' => $key,
    //       'compare' => $compare,
            'value' => $value,
        ),
        ) ,
    );


    $wp_query= new Wp_Query($filterargs);
    $qv=$wp_query->query_vars;

    while(have_posts()) : the_post();
    the_title();
    wp_reset_postdata();
    endwhile; 
    die();
}

The problem I'm facing is that the query keeps getting reset every time a user clicks on an input box with the id brand. What I want to do is to modify the query and re-run it. At this point i have not written the code to 'unmodify' the code when a checkbox is unchecked.

1 Answer 1

0

You can use wp_localize_script to save your current query to JS variable. Then you should send it using ajax and modify it and send it back to have access to it in the future.

global $wp_query;
wp_localize_script( 'ajax-pagination', 'ajaxpagination', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'query_vars' => json_encode( $wp_query->query )
));

This article should help you handle the issue. Especially part with query_vars there is quite good explanation.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.