I want the user to tick the child cat only, but I'd like to be able to display the parent cat based on the child cat. This is within the loop.
There's a function called
get_category_parents that will return a list of parents based on the ID. You can then loop through this list to display the parents.
get_category_parents() is a function which returns the category's parent based on the cat ID.
So in this case to make it adaptable, we use
get_queried_object_id() which will output the cat ID (number) of current object.
It's as simple as :
$parents = get_category_parents( get_queried_object_id()); if ( ! is_wp_error( $parents )) echo $parents;
It's good practice to implement the WP_Error fallback, mostly to avoid abritratry code execution.
A little PHP breakdown for those beginning:
- we declare the variable
$parentswill equal everything between the "=" sign and next semi-colon ";"
get_queried_object_id()returns the current object id (current category number)
- That number is piped in
get_category_parents()-> i.e get_category_parents('26')
- Last function returns name category 26 parent's name -> say 'Master Category' for example
- Semi-colon ! So end of this 'loop', simple way to think of it :
$parents = get_category_parents(26) ->
$parents = 'Master Category'
i'll quickly breeze through the last part, you're all smart cookies eager to figure it all out on your own ;)
End of story !