Skip to content

Instantly share code, notes, and snippets.

@halfempty
Created October 8, 2012 19:41
Show Gist options
  • Save halfempty/3854488 to your computer and use it in GitHub Desktop.
Save halfempty/3854488 to your computer and use it in GitHub Desktop.
WordPress Is Category or Subcategory
function is_category_or_subcategory($targetcategory) {
if ( is_category() ) :
// echo '<p>the target slug is: '. $targetcategory . '.</p>';
$targetid = get_category_by_slug($targetcategory);
// echo '<p>the target id is: '. $targetid->term_id . '.</p>';
$targetid = strval($targetid->term_id);
$id = get_query_var('cat');
// echo '<p>this id is: '. $id . '.</p>';
$chain = mca_category_parents($id);
// print_r($chain);
if ( in_array_r($targetid, $chain) ) {
// echo '<p>found</p>';
return true;
} else {
// echo '<p>not found</p>';
return false;
}
endif;
}
function mca_category_parents($id, $chain = array() ) {
$parent = get_category( $id );
if ( is_wp_error( $parent ) ) return $parent;
if ( $parent->parent && ( $parent->parent != $parent->term_id ) ) {
$chain[] = mca_category_parents( $parent->parent);
}
$chain[] = $parent->term_id;
return $chain;
}
function in_array_r($needle, $haystack, $strict = true) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment