// get the current category parents
$realparents = get_category_parents(get_query_var('cat'), false);
// could be something like kids/clothing/woman's
// create empty array
$realparents_array = array();
// create variable for final parent
$finalparent = '';
if (strpos($realparents, '/') !== false) {
$realparents_array = array_filter(explode('/', $realparents));
} else {
$realparents_array[0] = $realparents;
}
$i = count($realparents_array); // if 1, echo out [0] array, else echo
// 2nd last array
if ($i == 1)
{
$finalparent = $realparents_array[0];
}
else {
$finalparent = $realparents_array[$i-2]; // get
}
$finalparentid = get_category_id($finalparent);
Friday, March 28, 2014
Wordpress - get parent category
I've had an issue where get_the_category() didn't seem to work right for me. To fix this I used get_query_var('cat'), false and with that I used get_category_parents. I created an array and checked for the forward slash and divide the string into that array, with array_filter(explode('/', parents)) otherwise if there are no forward slashes, assign the string to the array. I then counted the array, if it is one(in case there is only one parent), the parent equals the first in the array, else (if there are 2 or more levels of category), use the count and minus 2, to get the 2nd last (parent above) the current category. With that information I got the id.
Labels:
wordpress
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment