Blog

«Return to Blog ListFilter 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.

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

Filter News by Category

'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

  
 $newslist));
    } else {
    echo 'Please enable WP-PageNavi!';
    } ?> 

Tags:

We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept