get_object_taxonomies,以及如何检索具有分级而非分级分类法的父或子?

时间:2019-01-21 10:35:19

标签: php wordpress

我需要在我的产品文章中添加一些来自自定义分类法的信息。我有一个函数,可以为我提供分类法对象,并且可以满足我的所有需求。

这是我的实际代码:

function get_tax_terms_for_the_product() {
// Get post by post ID.
if ( ! $post = get_post() ) {
    return '';
}

// Get post type by post.
$post_type = $post->post_type;

// Get post type taxonomies.
$taxonomies = get_object_taxonomies( $post_type, 'objects' );

$out = array();

foreach ( $taxonomies as $taxonomy_slug => $taxonomy ){

    // Get the terms related to post.
    $terms = get_the_terms( $post->ID, $taxonomy_slug );

    if ( ! empty( $terms ) ) {
        foreach ( $terms as $term ) {
            if( $term->parent == 0  ) {
              continue;
            }
            $out[] = sprintf( '<li>%1$s</li>',
                esc_html( $term->name )
            );
        }
    }
}
return implode( '', $out );
}

我遇到的问题是这个问题:当分类法是分层的时,我只想显示子术语,如果分类不是分层的,则显示父母。

我该如何实现?有提示吗?

致谢。

编辑:问题解决了,谁在乎呢?

function get_tax_terms_for_the_product() {
// Get post by post ID.
if ( ! $post = get_post() ) {
    return '';
}

// Get post type by post.
$post_type = $post->post_type;

// Get post type taxonomies.
$taxonomies = get_object_taxonomies( $post_type, 'objects' );

$out = array();

foreach ( $taxonomies as $taxonomy_slug => $taxonomy ){

    // Get the terms related to post.
    $terms = get_the_terms( $post->ID, $taxonomy_slug );

    if( is_taxonomy_hierarchical( $taxonomy_slug )) {

        if ( ! empty( $terms ) ) {
            foreach ( $terms as $term ) {
                if( $term->parent == 0  ) {
                  continue;
                }
                $out[] = sprintf( '<li>%1$s</li>',
                    esc_html( $term->name )
                );
            }
        }
    }

    if( ! is_taxonomy_hierarchical( $taxonomy_slug )) {

        if ( ! empty( $terms ) ) {
            foreach ( $terms as $term ) {

                $out[] = sprintf( '<li>%1$s</li>',
                    esc_html( $term->name )
                );
            }
        }
    }
} return implode( '', $out );
}

0 个答案:

没有答案
相关问题