In yesterday’s post, I shared how to determine if a given term has a child term. The idea behind doing this is to check to see if a given WordPress term has a child and if the child is actively applied to the post (or post type) in question.
But there’s a caveat that I didn’t mention:
Just because a term has a child doesn’t mean the term itself is actually active.
This means that you could technically be getting a false positive if you’re using the previous method as your sole means to determine if a term has a child. Instead, you need to do one more thing: Check to see if the post has the term applied to it.
If The Post Has a Term…
Before actually looking at code for how to do this, I think it’s helpful to outline what it is that we’re actually going to do:
- We’re going to load up all of the terms that exist for a given post type
- For each term, we’ll determine if the term has a child
- If the post has a child, we need to determine if the term is actively applied to the post
- If the term if applied to the post, we’ll store it in one index of an array
- Otherwise, we’ll store it in a different index of the array
To get started, we’ll setup a function that will accept a post ID as an argument since that’s what we’ll be using to evaluate its terms:
After that, we’ll prepare an array that will be used to store the active terms and the inactive terms.
Next, we need to retrieve all of the terms that are associated with the post – this is similar to what we did in yesterday’s post.
After that, we can loop through each of the terms to determine if it has a child. If so, we then need to look to see if the child term is applied to the post or not. We use the has_term function to do this.
If so, then we’ll stick it in one index of the array; otherwise, we’ll place it in the other index of the array.
From there, we’ll return the parent array so that we can do as we please with whatever the calling method does with this information.
Note that the code above is only expecting there to be one-level of children. If you’re looking to deal with more than that, then the same logic applies; however, you may want to look at using a recusive method to grab all of the children.
Regardless, this should be enough code to get you started to determine if a given WordPress post has a term actively applied to it.
Leave a Reply
You must be logged in to post a comment.