Skip to content

Instantly share code, notes, and snippets.

@steve-brett
Last active May 22, 2020 15:45
Show Gist options
  • Save steve-brett/e034fe106269dc056436ed931c6f60a4 to your computer and use it in GitHub Desktop.
Save steve-brett/e034fe106269dc056436ed931c6f60a4 to your computer and use it in GitHub Desktop.
Filter custom post type by taxonomy
<?php
/**
* Adds admin area filtering for CPT taxonomies.
*
* @param string $post_type The post type slug.
* @return void
*/
function filter_cpt_by_taxonomies( $post_type ) {
// Apply this only on a specific post type
if ( 'example_post_type' !== $post_type ) {
return;
}
// A list of taxonomy slugs to filter by
$taxonomies = array( 'article-categories', 'article-authors', 'locations', );
foreach ( $taxonomies as $taxonomy_slug ) {
$params = array(
'show_option_all' => get_taxonomy($taxonomy_slug)->labels->all_items,
'hide_empty' => true,
'hierarchical' => 1,
'show_count' => true,
'orderby' => 'name',
'name' => $taxonomy_slug,
'value_field' => 'slug',
'taxonomy' => $taxonomy_slug,
);
if ( isset($_GET[$taxonomy_slug]) ) {
$params['selected'] = $_GET[$taxonomy_slug]; // choose selected taxonomy by $_GET variable
}
wp_dropdown_categories($params);
}
}
add_action( 'restrict_manage_posts', 'filter_cpt_by_taxonomies' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment