0

Having a custom post type 'pubs' with custom taxonomy 'types' in which admin enter parent terms and their child terms. Using this code to get all the terms of current post type:

$object_terms = wp_get_object_terms($post->ID, 'types', array('fields' => 'all'));
    if ($object_terms) {
        echo '' . '' . '' ;
        $res = '';
        foreach ($object_terms as $term) {
            $res .=  $term->name . ',';
        }
        echo rtrim($res,' ,').'' . '';
    }

this code displays both parent & child terms. Is there any way to exclude parent terms from the result? I need the code to display only child terms related to the current post.

1 Answer 1

2

Each term object has a parent attribute which is set to 0 in case it's a parent root term or the ID of the parent in case it is a child term. So, if you have only one level of child terms then you can check for that attribute to not be equal to 0 in which case the term has a parent.

$object_terms = wp_get_object_terms( $post->ID, 'types', array( 'fields' => 'all' ) );

if ( $object_terms ) {
    echo '' . '' . '' ; /* This line is completely useless. */
    $res = '';

    foreach ( $object_terms as $term ) {
        /* If parent would be 0 then this 'if' would evaluate to false */
        if ( $term->parent ) { 
            $res .=  $term->name . ','; /* You probably wanted ', ' here. */ 
        }
    }
    /* This is great. In this form the 'rtrim' is useless. 
       The two "concatenations" are null and completely useless.*/
    echo rtrim($res,' ,').'' . '';  
}

Extra:

function wt_get_child_terms( $post_id, $taxonomy = 'category', $args = array() ) {
    $object_terms = wp_get_object_terms( $post_id, $taxonomy, $args );
    $res = '';

    if ( $object_terms ) {      
        foreach ( $object_terms as $term ) {
            if ( $term->parent ) {
                $res .=  $term->name . ', ';
            }
        }
    }

    return apply_filters( 'wt_get_child_terms', rtrim( $res, ', ' ) );
}

echo wt_get_child_terms( $post->ID, 'types', array( 'fields' => 'all' ) );
2
  • thanks for replying. actually I'm not a php expert. if you can please give me the suggested code.
    – nisr
    Aug 15, 2015 at 17:03
  • You don't have to be "a php expert" to add a simple if statement although I have updated my response to include your modified snippet.
    – webtoure
    Aug 15, 2015 at 17:14

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.