Home › Forums › General Issues › Filtering issues which remove images and filters on page › Reply To: Filtering issues which remove images and filters on page
Ok, so the following is based on your code and my suggestion.
Before doing anything, backup your site.
You already have the code in your functions file to create the film custom post type.
So now you can add the following to your functions file:
########################
# Add Taxonmoies
########################
function register_taxonomies() {
$taxonomies = array(
array(
'slug' => 'genres',
'single_name' => 'Genre',
'plural_name' => 'Genres',
'post_type' => 'film',
'hierarchical' => true,
),
);
foreach( $taxonomies as $taxonomy ) {
$labels = array(
'name' => $taxonomy['plural_name'],
'singular_name' => $taxonomy['single_name'],
'search_items' => 'Search ' . $taxonomy['plural_name'],
'all_items' => 'All ' . $taxonomy['plural_name'],
'parent_item' => 'Parent ' . $taxonomy['single_name'],
'parent_item_colon' => 'Parent ' . $taxonomy['single_name'] . ':',
'edit_item' => 'Edit ' . $taxonomy['single_name'],
'update_item' => 'Update ' . $taxonomy['single_name'],
'add_new_item' => 'Add New ' . $taxonomy['single_name'],
'new_item_name' => 'New ' . $taxonomy['single_name'] . ' Name',
'menu_name' => $taxonomy['plural_name']
);
$rewrite = isset( $taxonomy['rewrite'] ) ? $taxonomy['rewrite'] : array( 'slug' => $taxonomy['slug'] );
$hierarchical = isset( $taxonomy['hierarchical'] ) ? $taxonomy['hierarchical'] : true;
register_taxonomy( $taxonomy['slug'], $taxonomy['post_type'], array(
'hierarchical' => $hierarchical,
'labels' => $labels,
'show_ui' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => $rewrite,
));
}
}
add_action( 'init', 'register_taxonomies' );
##########################
# Ajax filter Films
##########################
function filter_films() {
$args = array(
'post_type' => 'film',
'posts_per_page' => -1,
);
if( isset( $_POST['genre'] ) )
$args['tax_query'] = array(
array(
'taxonomy' => 'genres',
'field' => 'id',
'terms' => $_POST['genre']
)
);
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
?>
<h2><?php the_title(); ?></h2>
<?php
endwhile;
wp_reset_postdata();
else :
echo 'No films found matching your criteria.';
endif;
die();
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_filter_films', 'filter_films');
add_action('wp_ajax_nopriv_filter_films', 'filter_films');
The first part creates the custom taxonomy for Genres.
The second part handles the filtering which we’ll come to next.
Create a page called films.
Now create a template file called page-films.php, from here you can add the following code:
<?php
/**
* @package WordPress
Template Name: Films
**/
get_header();
?>
<div id="filters">
<?php
$genres = array(
'taxonomy' => 'genres',
);
$genres = get_categories( $genres );
?>
<?php foreach($genres as $genre): ?>
<input type="checkbox" value="<?php echo $genre->term_id; ?>" class="form-check-input genre" />
<label class="form-check-label" for="<?php echo $genre->cat_name; ?>"><?php echo $genre->cat_name; ?></label>
<?php endforeach; ?>
<a href="#" class="btn" id="reset_genre">Reset Genres</a>
</div><!-- /filters -->
<div id="ajax_filter_films">
<?php
$args = array(
'post_type' => 'film',
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
?>
<h2><?php the_title(); ?></h2>
<?php
endwhile;
wp_reset_postdata();
else :
echo 'No films found matching your criteria.';
endif;
?>
</div><!-- /ajax_filter_films -->
<?php
get_footer();
You can assign the template films to the page, but due to naming conventions, should work. I always add it as a fallback.
Now, in your footer you can add:
<script type="text/javascript">
//filter the films
jQuery(function($){
filter_data();
function filter_data()
{
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'filter_films';
var genre = get_filter('genre');
$.ajax({
type : "POST",
data : { action:action, genre:genre},
dataType : "html",
url : '<?php echo admin_url('admin-ajax.php');?>',
success : function(data) {
//alert(this.data);
jQuery("#ajax_filter_films").html(data);
},
error : function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
return false;
}
function get_filter(class_name)
{
var filter = [];
$('.'+class_name+':checked').each(function(){
filter.push($(this).val());
});
return filter;
}
$('.form-check-input').click(function(){
filter_data();
});
$("#reset_genre").click(function(){
// get the current selected values
var genre = [];
$('.genre:checked').each(function(){
genre.push($(this).val());
});
// loop through and remove the selected checkobox
var i;
for (i = 0; i < genre.length; i++) {
$(".genre:checkbox[value="+genre[i]+"]").parent().removeClass('selected'); //remove the highlighted lable
$(".genre:checkbox[value="+genre[i]+"]").prop("checked", false); //uncheck the hidden checkbox
}
// reset the array
genre = [];
console.log(genre); //debug
// update the filter
filter_data();
});
});
</script>
I’d probably flush the permalinks!
You can now go to films within wp-admin and you should see a menu option called Genres.
Add the ones you need
Edit your films and assign one/multiples.
Go to the films page on the front end (its basic but gives you the idea).
You should now see all the films you’ve added plus a bunch of checkboxes.
Tick one or many and the results should filter!
The code is completely tested and works with a fresh WP install and the Twentytwentyone theme.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.