自定义帖子类型,显示父类和子类


Wordpress - custom post type, displaying the parent and child categories

所以我对Wordpress相当陌生,但到目前为止已经能够自己解决大多数问题。

我有一个自定义的帖子类型-我们称之为Machines。在这些机器中,有一个类别叫做Machine_type。假设我创建了一个名为Scissor Lifts的机器类型,然后另一个名为electric scissor lifts的机器类型,它是scissor lifts的子机器类型。

我想在单个帖子页面上显示此信息-因此在electric scissor lifts页面上,我想显示面包屑,如机器-剪刀升降机-电动剪刀升降机。但这似乎几乎是不可能的!我尝试过使用许多不同的教程,但他们似乎总是显示Machines - - - Final machine name,没有实际的2个类别,我想显示!

似乎有点疯狂,没有简单的内置调用类别和子类别!我用的是这个:

<?php 
    $terms = get_the_terms( $post->ID , 'machine_type' ); 
    foreach ( $terms as $term ) {
        $term_link = get_term_link( $term, 'machine_type' );
        if( is_wp_error( $term_link ) )
            continue;
        echo '<p>Machine Type: <a href="' . $term_link . '">' . $term->name . '</a></p>';
    } 
?>

但是这显然只是转储了所有的信息,没有办法很好地分离父和子类别。

编辑:

这个问题的更新:我终于找到了一些代码,似乎它正在解决正确的问题:

 <?php 
// get top level terms
$parents = get_terms( 'machine_type', array( 'parent' => 0 ) );
// get post categories
$categories = get_the_terms( $post->ID, 'machine_type' );
// output top level cats and their children
foreach( $parents as $parent ):
// output parent name and link
echo '<a href="' . get_term_link( $parent ) . '">' . $parent->name . '</a>: ';
// initialize array to hold child links
$links = array();
foreach( $categories as $category ):
    if( $parent->term_id == $category->parent ):
        // put link in array
        $links[] = '<a href="' . get_term_link( $category ) . '">' . $category->name .      '</a>';
    endif;
endforeach;
// join and output links with separator
echo join( ', ', $links );
endforeach;
?> 

然而,它的输出并不完全正确。例如,在一个被归类为臂架升降机和铰接式电动臂架升降机的机器上,它现在显示:"臂架升降机:铰接式臂架(电动)剪刀升降机:蜘蛛升降机:"

所以它增加了另外两个不适用于这台机器的类别。什么好主意吗?

$wcatTerms = get_terms('product_cat', array('hide_empty' => 0, 'orderby' => 'ASC',  'parent' =>0));
foreach($wcatTerms as $wcatTerm) : 
    echo $wcatTerm->name;
    $wsubargs = array('hierarchical'=>1,'show_option_none'=>'','hide_empty'=>0,'parent'=>$wcatTerm->term_id,'taxonomy'=>'product_cat');
    $wsubcats = get_categories($wsubargs);
    foreach ($wsubcats as $wsc):
        echo $wsc->name;
    endforeach;
endforeach; 

这可能对你有帮助

<?php 
    /********************** List out the parent and child inside parent ***/
    $taxonomyName = "your_taxonomy";
    $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); 
    if ($term->parent == 1) {  
    wp_list_categories('taxonomy=your_taxonomy&depth=1&show_count=0
    &title_li=&child_of=' . $term->term_id);
    } else {
    wp_list_categories('taxonomy=your_taxonomy&show_count=0
    &title_li=&child_of=' . $term->parent); 
    }
    ?>