Create AJAX Gallery Filtering and Load More — a practical guide to Create AJAX Gallery Filtering and Load More themes tutorial with clear examples you can reuse in real projects.
Build an AJAX gallery system that loads more projects and filters them using custom taxonomies such as Type, Material, Service, and Category.
// ===================================
// set the news more posts ajax function
// ===================================
add_action('wp_ajax_get_gallery_more_posts' , 'get_gallery_more_posts');
add_action('wp_ajax_nopriv_get_gallery_more_posts','get_gallery_more_posts');
function get_gallery_more_posts(){
$total_count = 0;
$ppp=12;
$args = array(
'post_status' => 'publish',
'post_type' => 'projects',
'posts_per_page' => $ppp,
'order' => 'DESC',
);
if(isset($_POST['offset']) && !empty($_POST['offset'])) {
$args['offset'] = $_POST['offset'];
}
$args['tax_query'] = array( 'relation'=>'AND' );
if(isset($_POST['gallery_type']) && !empty($_POST['gallery_type'])) {
$args['tax_query'][] = array(
'taxonomy' => 'type',
'field' => 'term_taxonomy_id',
'operator' => 'AND',
'terms' => explode(',',$_POST['gallery_type'])
);
}
if(isset($_POST['gallery_material']) && !empty($_POST['gallery_material'])) {
$args['tax_query'][] = array(
'taxonomy' => 'material',
'field' => 'term_taxonomy_id',
'operator' => 'AND',
'terms' => explode(',',$_POST['gallery_material'])
);
}
if(isset($_POST['gallery_service']) && !empty($_POST['gallery_service'])) {
$args['tax_query'][] = array(
'taxonomy' => 'service',
'field' => 'term_taxonomy_id',
'operator' => 'AND',
'terms' => explode(',',$_POST['gallery_service'])
);
}
if(isset($_POST['gallery_category']) && !empty($_POST['gallery_category'])) {
$args['tax_query'][] = array(
'taxonomy' => 'categories',
'field' => 'term_taxonomy_id',
'operator' => 'AND',
'terms' => explode(',', $_POST['gallery_category'])
);
}
$result = array();
$Media_query = new WP_Query($args);
//echo '<pre>';
//print_r($Media_query);
$result['result'] = '';
if( $Media_query->have_posts() )
{
while ($Media_query->have_posts())
{
$Media_query->the_post();
$params['post_id'] = get_the_ID();
$result['result'] .= qrs_return_get_template_part( 'template-parts/content', 'gallery-list',$params);
}
}
wp_reset_postdata();
$result['offset'] = $ppp + $_POST['offset'];
$result['total_post'] = $Media_query->found_posts;
$result['query'] = $Media_query->request;
echo json_encode($result);
exit;
}