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

时间:2014-07-08 10:38:53

标签: php wordpress categories taxonomy

所以我对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;

?> 

然而,它输出的内容并不完全正确。例如,在一个被归类为动臂升降机和铰接式电动臂升降机的机器上,它现在显示:“动臂升力:铰接式动臂(电动)剪式升降机:高空作业:”

所以它增加了2个不适用于这台机器的其他类别。有什么想法吗?

2 个答案:

答案 0 :(得分:3)

$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; 

使用此选项可显示两个级别的类别名称和产品名称。

答案 1 :(得分:0)

这可能会有所帮助

<?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); 
    }
    ?> 
相关问题