apply filter on ajax result wordspress code example
Example: wordpress ajax filter code
add_action('wp_ajax_myfilter', 'misha_filter_function');
add_action('wp_ajax_nopriv_myfilter', 'misha_filter_function');
function misha_filter_function(){
$args = array(
'orderby' => 'date',
'order' => $_POST['date']
);
if( isset( $_POST['categoryfilter'] ) )
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $_POST['categoryfilter']
)
);
if( isset( $_POST['price_min'] ) && $_POST['price_min'] || isset( $_POST['price_max'] ) && $_POST['price_max'] || isset( $_POST['featured_image'] ) && $_POST['featured_image'] == 'on' )
$args['meta_query'] = array( 'relation'=>'AND' );
if( isset( $_POST['price_min'] ) && $_POST['price_min'] && isset( $_POST['price_max'] ) && $_POST['price_max'] ) {
$args['meta_query'][] = array(
'key' => '_price',
'value' => array( $_POST['price_min'], $_POST['price_max'] ),
'type' => 'numeric',
'compare' => 'between'
);
} else {
if( isset( $_POST['price_min'] ) && $_POST['price_min'] )
$args['meta_query'][] = array(
'key' => '_price',
'value' => $_POST['price_min'],
'type' => 'numeric',
'compare' => '>'
);
if( isset( $_POST['price_max'] ) && $_POST['price_max'] )
$args['meta_query'][] = array(
'key' => '_price',
'value' => $_POST['price_max'],
'type' => 'numeric',
'compare' => '<'
);
}
if( isset( $_POST['featured_image'] ) && $_POST['featured_image'] == 'on' )
$args['meta_query'][] = array(
'key' => '_thumbnail_id',
'compare' => 'EXISTS'
);
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
echo '<h2>' . $query->post->post_title . '</h2>';
endwhile;
wp_reset_postdata();
else :
echo 'No posts found';
endif;
the ( ) ;
}