如何从当前帖子类型的自定义分类中仅获取子项?

时间:2015-08-15 作者:nisr

具有自定义分类“类型”的自定义帖子类型“pubs”,管理员在其中输入父术语及其子术语。使用此代码获取当前职位类型的所有术语:

$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,\' ,\').\'\' . \'\';
    }
此代码同时显示父级和;子条款。有没有办法从结果中排除父项?我需要代码来显示与当前帖子相关的唯一子术语。

1 个回复
最合适的回答,由SO网友:webtoure 整理而成

每个术语对象都有一个parent 属性,如果是父根项,则设置为0;如果是子项,则设置为父项的ID。因此,如果只有一级子术语,则可以检查该属性是否不等于0,在这种情况下,该术语有一个父项。

$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,\' ,\').\'\' . \'\';  
}
额外费用:

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\' ) );

结束

相关推荐

Get_Terms()返回空数组

我已经阅读了所有关于显示自定义分类法术语的帖子,但它仍然不起作用。好的,下面是代码:<?php //part of template-offer.php $taxonomy = \'brand\'; $term_args=array( \'hide_empty\' => false, \'orderby\' => \'name\', \'order\' => \'ASC\' ); $tax_terms =