Farooq Ahmad Farooq Ahmad - 3 months ago 14
PHP Question

Get Posts by Meta Values using checkbox

In my wordpress theme i create two checkbox in sidebar for custom field value. Apple and Nokia are values for key name Brand.

Now i need when i check a box or multiple box it show all relative post?


Here is input code,


<form>
<input type="checkbox" name="mobile" value="nokia"
<?php
$args = array (
'meta_query' => array(
array(
'key' => 'brand',
'value' => 'nokia'
),
),
);
$query = new WP_Query( $args );
?>/> Nokia <br>


<input type="checkbox" name="mobile" value="apple"
<?php
$args = array (
'meta_query' => array(
array(
'key' => 'brand',
'value' => 'apple'
),
),
);
?>/> Apple <br>
</form>


This query is used to get post, How this is used in template file for showing checkbox result?

<?php $query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
get_template_part('content');
}
} else {
}
wp_reset_postdata();
?>

Answer

Here is the code

this should be in your template

    <form id='test'>
<input type="checkbox" name="t[]" value="Nokia" class="br">
<input type="checkbox" name="t[]" value="Sony" class="br">
<div class="mobile_brand">

</div>
</form>
<script type="text/javascript">
    jQuery(document).ready(function(){
        jQuery('.br').click(function(){
            jQuery('.contents').remove();
            var checked = jQuery('#test').serialize();
            jQuery.ajax({
                url:"<?php echo admin_url('admin-ajax.php'); ?>",
                data:"action=call_post&"+checked,
                success:function(obj){
                     var render_data = "<div class='contents'>";

                    // This is to watch your json object
                    console.log(obj);   

                    for(var i=0;i<obj.length;i++)
                    {
                        console.log(obj[i].post_title);
                        render_data+="<h4>"+obj[i].post_title+"</h4>";
                        render_data+="<p>"+obj[i].post_content+"</p>";
                    }
                    render_data+="</div>";
                    jQuery(render_data).appendTo('.mobile_brand');

                }
            });
        })
    });
</script>

This should be in your functions.php

add_action('wp_ajax_call_post','call_post');
add_action('wp_ajax_nopriv_call_post','call_post');
function call_post(){
    $test = $_REQUEST['mobile'];

    $args = array(
        'post_type'  => 'post',
        'meta_query' => array(
            array(
                'key'     => 'brand',
                'value'   => $test,
                // 'compare' => 'IN',
            ),
        ),
    );

$query = new WP_Query( $args );
wp_send_json($query->posts);

}

This is just sample code for you. You need to render data by iterating JSON.

Comments