0

I'm creating a property theme and I have a hierarchical taxonomy 'property_location' registered for the custom post type 'property'. Each property will be assigned a location through this tax, which may have one or more parents in a hierarchical fashion. So for instance if I assign the location term of 'Springs' to a property, which is a child term of 'Gauteng', it should give me

Springs, Gauteng

And if Gauteng happens to be a child term of 'South Africa', it should give me

Springs, Gauteng, South Africa

But if I just assign the 'Gauteng' term (assuming it is a child term of the 'South Africa' term, it should give me

Gauteng, South Africa

So my question is how would I write a function smart enough to find the lowest level location term assigned to a property and get its parent terms in order? Is there any Wordpress functions that would help?

1 Answer 1

0

The wpse244577_list_terms() function below uses wp_list_categories() to do the heavy lifting, then modifies the results so that the terms are in reverse order of the hierarchy.

Place this code in a plugin or your theme's functions.php file:

/**
 * Lists term links for a taxonomy in reverse order of hierarchy
 * 
 * Based on https://developer.wordpress.org/reference/functions/wp_list_categories/#comment-1169    
 * @param $taxonomy string taxonomy name
 * @param $separator string separator for terms
 */
function wpse244577_list_terms( $taxonomy, $separator = ', ' ) {        

    // Get the term IDs assigned to post.
    $post_terms = wp_get_object_terms( get_the_ID(), $taxonomy, [ 'fields' => 'ids' ] );

    if ( ! empty( $post_terms ) && ! is_wp_error( $post_terms ) ) {

        $terms = wp_list_categories( [
                'title_li'  => '',
                'style'     => 'none',
                'echo'      => false,
                'taxonomy'  => $taxonomy,
                'include'   => $post_terms,
                'separator' => $separator,
        ] );

        $terms = rtrim( trim( str_replace( $separator, $separator, $terms ) ), ', ' );
        $terms = explode( $separator, $terms );
        $terms = array_reverse( $terms );
        $terms = implode( $separator, $terms );

        echo  $terms;
    }
}

To use the function, call it within the loop of your theme, passing the desired taxonomy name as the first parameter:

wpse244577_list_terms( 'property_location' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.