Forked from koskinenaa/wordpress-filter-custom-post-types-by-custom-taxonomies.php
Created
April 27, 2020 07:24
-
-
Save golchha21/07b6fb7a4144ce0bae32ca2c54236c28 to your computer and use it in GitHub Desktop.
Add filtering by custom taxonomies to a post type. Note when registering the custom taxonomies 'query_var' should not be set to false. If so, this function won't work,
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Add taxonomy filtering to custom post types | |
* | |
* Original example for one post type, https://generatewp.com/filtering-posts-by-taxonomies-in-the-dashboard/ | |
* | |
*/ | |
function filter_cpt_by_taxonomies( $post_type, $which ) { | |
// Affected post types | |
$post_types = array( | |
'my_post_type', | |
'my_another_post_type' | |
); | |
// Apply this only on a specific post type | |
if ( ! in_array( $post_type, $post_types ) ) { | |
return; | |
} | |
// Get associated taxonomies names | |
$taxonomies = get_object_taxonomies( $post_type, 'object' ); | |
// Bail early | |
if ( ! $taxonomies ) { | |
return; | |
} | |
// Loop taxonomies | |
foreach ( $taxonomies as $taxonomy ) { | |
// Retrieve taxonomy terms | |
$terms = get_terms( $taxonomy->name ); | |
// Bail early | |
if ( ! $terms || is_wp_error( $terms ) ) { | |
continue; | |
} | |
// Display filter HTML | |
echo "<select name='{$taxonomy->name}' id='{$taxonomy->name}' class='postform'>"; | |
echo '<option value="">' . sprintf( esc_html__( 'Show All %s', 'textdomain' ), $taxonomy->label ) . '</option>'; | |
foreach ( $terms as $term ) { | |
printf( | |
'<option value="%1$s" %2$s>%3$s (%4$s)</option>', | |
$term->slug, | |
( ( isset( $_GET[$taxonomy->name] ) && ( $_GET[$taxonomy->name] == $term->slug ) ) ? ' selected="selected"' : '' ), | |
$term->name, | |
$term->count | |
); | |
} | |
echo '</select>'; | |
} | |
} | |
add_action( 'restrict_manage_posts', 'filter_cpt_by_taxonomies' , 10, 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment