Created
November 8, 2019 11:50
-
-
Save morgyface/2018864376d6961889f224ba5b0273da to your computer and use it in GitHub Desktop.
WordPress | Category term filter
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
| <?php | |
| // A filter function to remove certain terms or categories | |
| function categories_filtered( $post_id, $term_slug ) { | |
| $category_objects = null; | |
| $categories = get_the_category( $post_id ); // Get the categories assigned to the post | |
| if ( ! empty( $categories ) ) { | |
| $category_ids = wp_list_pluck( $categories, 'term_id' ); // Convert list into array of cat IDs | |
| $excluded = get_category_by_slug( $term_slug ); // Get category object of term to be excluded | |
| $excluded_id = $excluded->term_id; // Get the ID of the excluded term | |
| $key = array_search( $excluded_id, $category_ids ); // Now get the array key of the excluded category | |
| if( $key ) { | |
| unset( $category_ids[$key] ); // If the key of the excluded category exists lets remove it | |
| $args = array( | |
| 'include' => $category_ids, | |
| 'exclude' => $excluded_id | |
| ); | |
| } else { | |
| // Doesnt look like the excluded term is present in the array | |
| $args = array( | |
| 'include' => $category_ids | |
| ); | |
| } | |
| $categories = get_categories( $args ); | |
| if ( ! empty( $categories ) ) { | |
| $category_objects = $categories; | |
| } | |
| } | |
| return $category_objects; | |
| } | |
| ?> |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
WordPress category filter function
I put this together as I was frustrated with the Uncategorised category getting in the way
Hopefully the comments will help to explain what is going on.
Add the above to your theme's
functions.phpfile and then use it like so:$categories = categories_filtered( $post->ID, 'uncategorised' );This will return an array of category objects the same as
get_the_categorywould minus the excluded category. If no objects are found it will returnnull.👍