I’m not completely sure that you do actually need get_terms()
twice. It looks very ineffecient and overboard. I don’t know if you need this for ordering purposes, but still, there are better ways of doing this without hitting the db so hard. One alternative is to make one call to get_terms()
and then use usort()
to sort your terms by parent. But this is beyond what your question is about.
There are a couple of ways to exclude the parent terms
-
Simply use the
exclude
parameter inget_terms()
to exclude the parent categories. If your parents have id’s 1 and 2, then you would add'exclude' => [1, 2],
to your arguments inget_terms()
· (Note, the new short array syntax is only available from PHP 5.4. For older versions use'exclude' => array( 1, 2 ),
) -
You can also just loop over the parents. If your parents are top level terms, then their parent id will be
0
, so you can simply add the following in yourforeach
loopif ( $prod_cat->parent == 0 ) continue;
Alternatively, you can use their respective ids to skip them
if ( $prod_cat->term_id == 1 || $prod_cat->term_id == 2 ) continue;