Created
October 8, 2012 19:41
-
-
Save halfempty/3854488 to your computer and use it in GitHub Desktop.
WordPress Is Category or Subcategory
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
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