I have this code which is located on the search.php page and retrieves all the categories for each post and echo’s out a link to the first category:
$category = get_the_category(); //print_r($category);
if ($category) {
echo '<a href="' . get_category_link( $category[0]->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category[0]->name ) . '" ' . '>' . $category[0]->name.'</a> ';
What I need to do is use a similar code but that gets the child-most/deepest category in the array?
This is the array thats printed out:
[0] => stdClass Object
(
[term_id] => 170
[name] => ACS Series Suspended & Crane Scales - EC Approved
[slug] => uwe-acs-series-suspended-crane-scales
[term_group] => 0
[term_taxonomy_id] => 170
[taxonomy] => category
[description] =>
[parent] => 3
[count] => 4
[object_id] => 1578
[cat_ID] => 170
[category_count] => 4
[category_description] =>
[cat_name] => ACS Series Suspended & Crane Scales - EC Approved
[category_nicename] => uwe-acs-series-suspended-crane-scales
[category_parent] => 3
)
[1] => stdClass Object
(
[term_id] => 3
[name] => Crane Scales
[slug] => crane-scales
[term_group] => 0
[term_taxonomy_id] => 3
[taxonomy] => category
[description] =>
[parent] => 0
[count] => 53
[object_id] => 1578
[cat_ID] => 3
[category_count] => 53
[category_description] =>
[cat_name] => Crane Scales
[category_nicename] => crane-scales
[category_parent] => 0
)
As you can see, one category has parent->3 and the other has parent->0. How do I use the above query to print out the link only for a category with parent->3?
Its probably quite simple but its a bit over my head. Any help would be greatly appreciated!
Thanks
Dave
Might get_category_parents() be helpful? It outputs a list of all hierarchical parents of the given category.
got a result on stack overflow which worked spot on thanks to @poelinca. code is below incase anybody else has the same issue:
Add this function in you’re theme/functions.php file :
Then let’s say as in you’re example in theme/search.php you do
@chip bennett, thanks for your input, I did try this but struggled to get it working how I needed (removing the separators).
Thanks,
Dave