Skip to content

Instantly share code, notes, and snippets.

@joliesky
Last active December 21, 2015 09:09
Show Gist options
  • Save joliesky/6283557 to your computer and use it in GitHub Desktop.
Save joliesky/6283557 to your computer and use it in GitHub Desktop.
Wordpress - Ability to get category and all sub-categories
/*
Snippet Name: Category or Subcategory
Description: Gets the category and all subcategories of a cat_ID
Usage: Ideal if you are trying to put code only on the categories of a cat and it's children, in lieu of doing an array of all the children. Put the following code in functions.php or a plugin.
*/
<?php if (!function_exists('is_category_or_sub')) {
function is_category_or_sub($cat_id = 0) {
foreach (get_the_category() as $cat) {
if ($cat_id == $cat->cat_ID || cat_is_ancestor_of($cat_id, $cat))
return true;
}
return false;
}
} ?>
/*
example: To add code to category 1 and it's children
<?php if(is_category_or_sub(1)) {
//put code here
} ?>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment