Im trying to check if ‘categoryone’ has a parent.
Right know I can check and see that there is a category called categoryone, but not if categoryone has a parent category.
I have tried to code something like the code bellow.
$tid = term_exists('categoryone', 'category', 0);
$term_ids = [];
if ( $tid !== 0 && $tid !== null )
{
$term_ids[] = $tid['term_id'];
}
else
{
// If there is not a parent category!
$insert_term_id = wp_insert_term( 'categoryone', 'category' );
if ( ! is_wp_error )
$term_ids[] = $insert_term_id;
}
wp_set_post_categories( $insert_id, $term_ids );
You may use something like this (Paste this in your
functions.php
file)Call this from template
Check Children
Call this from template
You can use the get_category() to fetch current category details by passing term_id
get_category() returns the object like below taken from reference site
EDIT To get the child categories you can use get_categories() by passing the the arguments array.
parent
Well you can use
get_category_parents()
(take a look at the link to read over the arguments, etc). This will return a list of all the parents in hierarchical order. In that case, if you just want the most immediate parent category you could do something like this:This will echo out the 1st parent category (the one directly above your current category).
To be clear:
in
get_category_parents()
– arg 1 is the category id (i just used
$cat
arbitrarily)– arg 2 is if you would like wp to add a link to each returned parent category
– arg 3 is the delimiter used to separate the returned categories, if any
in
explode()
– arg 1 is the delimiter to look for to separate the string in an array
– arg 2 is the source string to separate
Happy coding!
Use below code to check parent and children of a category.
@ M Khalid Junaid
To expand on your answer, I used the basis of your code to check if it the category has no parents and is a top tier item in a category/taxonomy heriarchy. I am including this because it is what I was looking for when I stumbled across this thread and maybe someone else is doing the same.
Output
Tier 1: Category Name
Tier 1: Another Category Name
Tier 1: All Top Level Categories