Skip to content

Instantly share code, notes, and snippets.

@kellenmace
Created June 25, 2015 13:05
Show Gist options
  • Save kellenmace/c4e0eee55e5e357829dd to your computer and use it in GitHub Desktop.
Save kellenmace/c4e0eee55e5e357829dd to your computer and use it in GitHub Desktop.
Create a custom taxonomy dropdown in WordPress
<div class="all-tools">
<?php
// If the taxonomy term has previously been selected from the dropdowm menu, grab it
$term = isset( $_GET[ 'tools' ] ) ? sanitize_text_field( $_GET[ 'tools' ] ) : false;
// In this section, set selected and taxonomy_query values before creating the taxonomy dropdown & getting WP_Query results
$selected = '';
$tax_query = '';
if ( $term ) {
// Get all posts with the selected taxonomy term
$term = get_term_by( 'slug', $term, 'tools' );
if ( ! empty( $term->name ) ) {
// Set the 'selected' value that we'll use to show which option in the dropdown menu is the currently selected one
$selected = $term->name;
// Set the taxonomy to 'tools' and the term to the selected term. We'll use these to filter the posts, below
$tax_query = array(
array(
'taxonomy' => 'tools',
'terms' => $term,
),
);
}
}
?>
<form id="tool-category-select" class="tool-category-select" action="<?php the_permalink(); ?>" method="get">
<?php
// Create and display the dropdown menu using 'tools' for the taxonomy, and the selected value we set above
wp_dropdown_categories(
array(
'orderby' => 'NAME', // Order the items in the dropdown menu by their name
'taxonomy' => 'tools', // Only include posts with the taxonomy of 'tools'
'name' => 'tools', // This field is needed for submitting the form
'value_field' => 'slug', // This field is needed for submitting the form
'show_option_all' => 'All Tools', // Text the dropdown will display when none of the options have been selected
'selected' => $selected, // Set which option in the dropdown menu is the currently selected one
) );
?>
<input type="submit" name="submit" value="view" />
</form>
</div>
<section id="tools-listing">
<?php
// Get all posts with a post type of 'tool', a taxonomy of 'tools', and the taxonomy term that was selected in the dropdown
$tool_query = new WP_Query(
array(
'post_type' => 'tool',
'posts_per_page' => 1000,
'tax_query' => $tax_query,
)
);
?>
<!-- Loop through every post that matched our query -->
<?php if ( $tool_query->have_posts() ) : while ( $tool_query->have_posts() ) : $tool_query->the_post(); ?>
<!-- Display each post's title and content - you can change this section to display whatever post content you want -->
<article class="tool-entry">
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
</article>
<?php endwhile; endif; ?>
</section>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment