Manik
Manik

Reputation: 523

Use Ajax in Wordpress

My current query is

$args=array(
    'post_type'=>'product',
    'post_per_page'=>'10',
    'tax_query' => array(
            array(
            'taxonomy' => 'product_cat',
            'field'    => 'slug',
            'terms'    => 'car',
                ),
                        ),
            );
    $loop=new WP_Query($args);

And i have check-boxes Bus<input type="checkbox" class="ve-select" value="bus">

Boat<input type="checkbox" class="ve-select" value="boat">.

Currently what i do is when some one click on check box i reload the page using javascript and pass the value through 've' variable.

$args=array(
    'post_type'=>'product',
    'post_per_page'=>'10',
    'tax_query' => array(
            array(
            'taxonomy' => 'product_cat',
            'field'    => 'slug',
            'terms'    => $_REQUEST['ve'],
                ),
                        ),
            );
    $loop=new WP_Query($args);

Please any one can suggest how can i change the query and show the result without reloading .

Please help friends .

Upvotes: 0

Views: 82

Answers (1)

BlueSuiter
BlueSuiter

Reputation: 567

Please try the following Code::

in Your post_page

<script>
    function getPostList(val)
    {
        jQuery.ajax({
            url: '<?= admin_url('admin-ajax.php') ?>',
            data: {action:'my_action', term: val, secret: '<?php wp_create_nonce('listPost_byCat'); ?>'},
            method: 'POST',
            success: function(res){
                jQuery('#post-div').html(res);
            }
        });   
    }

    jQuery(document).ready(function(){
        jQuery('.ve-select).on('click', function(){
            getPostList(jQuery(this).val());
        });
    });
</script>

in functions.php

<?php
    add_action('wp_ajax_my_action', 'my_action_handler');
    add_action('wp_ajax_nopriv_my_action', 'my_action_handler');

    function my_action_handler()
    {
        if(wp_verify_nonce($_POST['secret'], 'listPost_byCat')) 
        {
            $args=array(
                'post_type'=>'product',
                'post_per_page'=>'10',
                'tax_query' => array(
                        array(
                            'taxonomy' => 'product_cat',
                            'field'    => 'slug',
                            'terms'    => $_POST['term'],
                        ),
                    ),
                );
            $loop=new WP_Query($args);

            if(!empty($loop))
            {
                foreach($loop as $post)
                {
                    echo $post->post_title() . '<br/>';
                }
            }
        }
    }
?>

Upvotes: 1

Related Questions