只有在应该有多个子项的情况下才显示一个子项

时间:2016-11-28 作者:Gregor Aitken

我希望有人能帮助我,我正试图让我的自定义帖子子类别显示,但似乎只能显示其中一个。有没有办法让我把它们都循环一遍?我是一个前端开发人员,这个PHP让我的大脑一团糟。(不知道你是怎么做到的)

功能如下,任何帮助都会很好。

/**
 * Get taxonomies terms links.
 *
 * @see get_object_taxonomies()
 */
function wpdocs_custom_taxonomies_terms_links() {
    // Get post by post ID.
    $post = get_post( $post->ID );


// 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 ) ) {
        $out[] = "<h2>" . $taxonomy->label . "</h2>\\n<ul>";
        foreach ( $terms as $term ) {
            $out[] = sprintf( \'<li><a href="%1$s">%2$s</a></li>\',
                esc_url( get_term_link( $term->slug, $taxonomy_slug ) ),
                esc_html( $term->name )
            );
        }
        $out[] = "\\n</ul>\\n";
    }
}
return implode( \'\', $out );
}

enter image description here

下面是我希望看到的子类别-Alpha Pizza是父类,子类别如下。enter image description here

1 个回复
SO网友:Dan.

假设您希望一次只显示一个分类法的术语,那么这将生成您想要的:

function my_theme_get_child_terms(){

    $return = \'\';
    $current_term = get_queried_object()->term_id;
    $term_info = get_term($current_term);
    $sub_categories = get_term_children( $current_term, $term_info->taxonomy );

    $return .= \'<h2>\' . $term_info->taxonomy . \'</h2><ul>\';
    foreach ( $sub_categories as $cat ) {
        $term = get_term_by( \'id\', $cat, $term_info->taxonomy );
         $return .= sprintf( \'<li><a href="%1$s">%2$s</a></li>\',
            esc_url( get_term_link( $cat, $term_info->taxonomy ) ),
            esc_html( $term->name )
    }
    $return .= \'</ul>\';

    return $return;
}
您需要将上述代码放入相关template file. E、 g。taxonomy.phpindex.php.