Filter posts by checkboxes in wordpress (Custom fields from ACF)

Filter posts by checkbox acf wordpress and ajax

As we discussed this in our earlier posts that in WordPress, sometimes we needs to filter the posts. We had done with the filter posts by taxonomy. You can have a look at that tutorial from here. In this tutorial, we will continue to work on the filter. We will “filter posts by checkboxes in WordPress”. The most important part is that we will make the checkbox by using the ACF plugin. If you are familiar with ACF plugin then you can download the plugin from WordPress repository for ACF Plugin.

Now follow these step:

Step 1 – Create the Checkbox

First of all, create the field with type checkbox using ACF plugin. We will use these checkbox data in the filtering process.

Step 2 – Render the checkbox on frontend

Insert the code below into your template file. This code will call the checkbox in the frontend that we created with the ACF plugin.

<div class="form-group col-md-12">
    <label class="col-md-2 control-label" for="region">Region</label>
    <div class="col-md-10">
        <div class="col-md-12">
            <?php
            $region = get_field_object('field_5594575c5d4ed');
            $region_name = $region['choices'];
            ?>
            <?php
            foreach ($region_name as $region_value)
            {
                ?>
                <div class="col-sm-3 select_check">
                    <input type="checkbox" name="post_region[]" id="post_region" class="checkboxes" value="<?php echo $region_value; ?>"><?php echo $region_value; ?>
                </div>
                <?php
            }
            ?>
        </div>
    </div>
</div>

Step 3 – Call the ajax

We have completed the view section. With the code above, your template is complete with the UI. The next step is to make the code work by calling the ajax with jquery. Copy and paste the following code into the footer.php file

<script type="text/javascript">
    jQuery(document).ready(function(event){
        jQuery(".search1").click(function(event){
            var arr_region = new Array; // Array For checked region
            event.preventDefault();
            var ajaxurl= '<?php echo admin_url("admin-ajax.php"); ?>';

            jQuery("input[name='post_region[]']:checked").each( function () {
                var tmp =jQuery(this).val();
                arr_region.push(tmp);
            });
            final_search_arr['region'] = arr_region;
            jQuery.ajax({
                url: ajaxurl, 
                dataType: "html",
                type: "POST",
                data:{
                    "search_array" : final_search_arr,
                    "action" : "get_keyword_data"
                },
                success: function(data){ alert(data); }
            });
        });
    });
</script>

Step 4 – Create ajax callback

In the above code, we had called an ajax function “get_keyword_data” . Now we have to make that function into the function.php file of your theme folder.

<?php
add_action('wp_ajax_get_keyword_data', 'get_keyword_data');
add_action('wp_ajax_nopriv_get_keyword_data', 'get_keyword_data');
function get_keyword_data() {
    extract($_POST);
    $selected_country = $selected_country; //get selected country
    $searched_array = $search_array; // get Arrray for region , Opp type and eligiblity
    /*  Make array Element for Region */
    $region_sel = $searched_array['region'];
    $tmp_arr_region = array();
    foreach ($region_sel as $value11) {
        $tmp_arr_region[] = $value11;
    }
    $region = implode(',', $tmp_arr_region);
    $values_region = explode(',', $region);
    $tmp_region = array();
    foreach ($values_region as $value12) {
        $tmp_region[] = array('key' => 'post_region', 'value' => $value12, 'compare' => 'LIKE');
    }
    $checkbox_array = array();
    $checkbox_array['region'] = $region_sel; // Selected Checkbox Region
    $checkbox_array['opp_type'] = $opp_type; // Selected Checkbox Opportunity type
    $checkbox_array['eligiblity'] = $eligiblity; // Selected Checkbox  Eligiblity
    $checkbox_array['country'] = $values_country; // Selected Checkbox selected_country
    $listing = new WP_Query(array('post_type' => 'opportunity', 'post_status' => 'publish', 's' => $keyword, //keyword search
    'compare' => 'LIKE', 'order' => 'ASC', 'orderby' => 'meta_value', 'meta_query' => array('relation' => 'AND', $tmp_region, //Region Checkbox Search
    $tmp_Opp_type, //Opp_type Checkbox Search
    $tmp_eligibility, //eligibility Checkbox Search
    $tmp_country, //country Checkbox Search
    ),));
    while ($listing->have_posts()):
        $listing->the_post();
        global $post;
        $post_id = $listing->post->ID;
        $type_cat = get_field('opportunity_type_category', $listing->post->ID, true);
        $region_name = get_field('post_region', $listing->post->ID, true);
        $eligibility_name = get_field('eligibility_student_level', $listing->post->ID, true);
        $country = get_field('country', $listing->post->ID, true);
        $listing_array = array();
        $listing_array['region'] = $region_name;
        $listing_array['opp_type'] = $type_cat;
        $listing_array['eligiblity'] = $eligibility_name;
        $listing_array['country'] = $country; // Selected Checkbox selected_country
        ////////////////////////// Check If blank(checkbox selection) is equal to blank1(Meta Query Result)/////////////////////////
        if (count(array_diff($checkbox_array['region'], $listing_array['region'])) == 0 && count(array_diff($listing_array['region'], $checkbox_array['region'])) == 0 && count(array_diff($checkbox_array['opp_type'], $listing_array['opp_type'])) == 0 && count(array_diff($listing_array['opp_type'], $checkbox_array['opp_type'])) == 0 && count(array_diff($checkbox_array['eligiblity'], $listing_array['eligiblity'])) == 0 && count(array_diff($listing_array['eligiblity'], $checkbox_array['eligiblity'])) == 0 && count(array_diff($checkbox_array['country'], $listing_array['country'])) == 0 && count(array_diff($listing_array['country'], $checkbox_array['country'])) == 0) {
            the_title();
        }
    endwhile;
}

Filter posts by checkboxes

The above tutorial teach us about the Filter posts by checkboxes in WordPress which is very useful for those who work as WordPress developer.