Created
January 27, 2020 08:14
-
-
Save raftaar1191/899fa2791bafaf9c20a981e8ef079a98 to your computer and use it in GitHub Desktop.
Filter to Sort CPT via taxonomies in CPT DashBoard area
This file contains hidden or 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 filter in the CPT | |
*/ | |
function CPT_filter_by_taxonomies( $post_type, $which ) { | |
// Apply this only on a specific post type | |
if ( 'CPT' !== $post_type ) { | |
return; | |
} | |
// A list of taxonomy slugs to filter by | |
$taxonomies = array( 'taxonomy-slugs-1', 'taxonomy-slugs-2' ); | |
foreach ( $taxonomies as $taxonomy_slug ) { | |
// Retrieve taxonomy data | |
$taxonomy_obj = get_taxonomy( $taxonomy_slug ); | |
$taxonomy_name = $taxonomy_obj->labels->name; | |
$terms = get_terms( $taxonomy_slug, 'hide_empty=0' ); | |
// Display filter HTML | |
echo "<select name='{$taxonomy_slug}' id='{$taxonomy_slug}' class='postform'>"; | |
echo '<option value="">' . sprintf( esc_html__( 'Show All %s', 'text_domain' ), $taxonomy_name ) . '</option>'; | |
foreach ( $terms as $term ) { | |
printf( | |
'<option value="%1$s" %2$s>%3$s (%4$s)</option>', | |
$term->slug, | |
( ( isset( $_GET[ $taxonomy_slug ] ) && ( $_GET[ $taxonomy_slug ] == $term->slug ) ) ? ' selected="selected"' : '' ), | |
$term->name, | |
$term->count | |
); | |
} | |
echo '</select>'; | |
} | |
} | |
add_action( 'restrict_manage_posts', 'CPT_filter_by_taxonomies', 10, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment