When your website means business.

«Return to Blog List Filter Custom Post Type with Dropdown Menu using Custom Taxonomy

A couple of years ago (but only a few posts back; yes, I’m terrible about posting) I posted Filter Custom Post Types with Dropdown Menu Using Custom Field Values. That technique used custom fields to filter posts. With a new project I’m working on, I need to make sure site editors can add categories as needed, then allow visitors to use those categories to filter posts on the front end. That meant a custom taxonomy was the only way to go, because I don’t want my client to have to call me every time they need to add a new category.

Once again, I was unable to find a complete solution anywhere. I started with my afore-mentioned filtering solution, but custom taxonomies are a lot more complex to work with than custom fields. For starters, I needed to create a dynamic select menu, and it had to make the selected option “selected.” I tried several versions before modifying a fairly common piece of code that allows us to get taxonomy terms. While it took a while to put all the pieces together, I’m pleased with its simplicity.

<h4>Filter News by Category</h4>
<form action="" method="GET" id="newslist">
<select name="newscat" id="newscat" onchange="submit();">
<option value="" <?php echo ($_GET['newscat'] == '') ? ' selected="selected"' : ''; ?>>Show all</option>
<?php 
    $categories = get_categories('taxonomy=news-category&post_type=news'); 
    foreach ($categories as $category) : 
    echo '<option value="'.$category->name.'"';
    echo ($_GET['newscat'] == ''.$category->name.'') ? ' selected="selected"' : '';
    echo '>'.$category->name.'</option>';
    endforeach; 
?>
</select>
</form>
<?php // let the queries begin 
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;  
if( !isset($_GET['newscat']) || '' == $_GET['newscat']) {
    $newslist = new WP_Query( array(
    'post_type' => 'news', 
    'posts_per_page' => 8,
    'orderby' => 'DATE',
    'paged' => $paged
    ) ); 
} else { //if select value exists (and isn't 'show all'), the query that compares $_GET value and taxonomy term (name)
    $newscategory = $_GET['newscat']; //get sort value
    $newslist = new WP_Query( array(
    'post_type' => 'news', 
    'posts_per_page' => 8,
    'orderby' => 'DATE',
    'paged' => $paged,
    'tax_query' => array(
        array(
        'taxonomy' => 'news-category',
        'field' => 'name',
        'terms' => $newscategory
        ) 
    ) 
    ));
}
if ($newslist->have_posts()) :
while ( $newslist->have_posts() ) : $newslist->the_post(); 
?>

SHOW RESULTS

<?php endwhile; 
else : 
echo 'There are no news items in that category.'; 
endif; 
?>  
<?php wp_pagenavi( array( 'query' => $newslist ) ); ?> 
<?php wp_reset_query(); ?>

Let me hear from you if you have comments or questions.

Tags:

Comments are closed.