1

Is there an existing function in WordPress to generate a list of taxonomy slugs ordered by parents > childs > subchilds in an array? I need to generate a URL structure for my custom post type in the format example.com/parents/childs/subchilds/postname.

I see the default post type in WordPress already does this but my custom post type is of "page" type.

So far I'm doing this:

$terms = get_the_terms($post->ID, 'scategory');   // scategory is my custom taxonomy     
$slugs = [];
foreach ( $terms as $term ) {
    $slugs[$term->term_id] = $term->slug;
}
ksort($slugs); // sorting by slug ids
$finalSlug = join( '/', $slugs ); // making rewrite rule slug for custom post type

By default, get_the_terms outputs terms in alphabetical order; that's why I sorted it by their keys, so that I can assume the terms with lower IDs as parents and others as children, but this isn't reliable in the long run.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.