如何在wp自定义Taxonamy中显示所选父项的子项

时间:2017-06-12 12:23:29

标签: php jquery ajax wordpress

我创建了一个自定义帖子类型:" Publication"及其分类学"出版 - 流派"

使用分类法选中我正在使用同位素js显示与其相关的帖子。

我已经在下拉列表中转换了分类法,并根据我能够显示帖子的选项进行了转换。

现在我的问题是: 例如:(父母及其子条款)

1. Vision
    a. Vision 1
    b. vision 2 
2. View 
     a. View 1 
     b. View 2

如果条款"愿景"然后在另一个下拉列表中选择,其中包含子项,应显示仅选择父项的子项,而不是其他项。

获取所有子学期:

foreach( get_terms( 'publication-genre', array( 'hide_empty' => false, 'parent' => 0 ) ) as $parent_term ) { 
     foreach( get_terms( 'publication-genre', array( 'child_of' => $terms[0],'hide_empty' => false, 'parent' => $parent_term->term_id ) ) as $child_term ) {
       echo "<option value='.".$child_term->slug."'>" . $child_term->name . "</option>\n";
      }
}

?>

获取家长:

<?php 
    $terms = get_terms("publication-genre", array( 'hide_empty' => false, 'parent' => 0 )); 
        $count = count($terms);
        if ( $count > 0 ){  
        foreach ( $terms as $term ) { 
        echo "<option value='.".$term->slug."'>" . $term->name . "</option>\n";
        }
    } 
?>
</select>

1 个答案:

答案 0 :(得分:0)

获取当前的term_id并检查当前term_id是否等于父和子词ID

//get current the term_id    
 $publication_genre_category_object=get_queried_object();
 $publication_genre_current_term_id = $publication_genre_category_object->term_id;

        foreach( get_terms( 'publication-genre', array( 'hide_empty' => false, 'parent' => 0 ) ) as $parent_term ) { 
             foreach( get_terms( 'publication-genre', array( 'child_of' => $terms[0],'hide_empty' => false, 'parent' => $parent_term->term_id ) ) as $child_term ) {
                 if($publication_genre_current_term_id  == $child_term->term_id)
                 {
                     $child_term_selected = "selected";
                 }
               echo "<option value='.".$child_term->slug."' ".$child_term_selected.">" . $child_term->name . "</option>\n";
              }
        }
         $terms = get_terms("publication-genre", array( 'hide_empty' => false, 'parent' => 0 )); 
            $count = count($terms);
            if ( $count > 0 ){  
            foreach ( $terms as $term ) { 
             if($publication_genre_current_term_id  == $term->term_id)
             {
                 $term_selected = "selected";
             }
            echo "<option value='.".$term->slug."' ".$term_selected.">" . $term->name . "</option>\n";
            }
        }