Skip to content

Instantly share code, notes, and snippets.

@morgyface
Created November 8, 2019 11:50
Show Gist options
  • Select an option

  • Save morgyface/2018864376d6961889f224ba5b0273da to your computer and use it in GitHub Desktop.

Select an option

Save morgyface/2018864376d6961889f224ba5b0273da to your computer and use it in GitHub Desktop.
WordPress | Category term filter
<?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;
}
?>
@morgyface
Copy link
Author

morgyface commented Nov 8, 2019

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.php file 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_category would minus the excluded category. If no objects are found it will return null.

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment