尝试获取按父术语 (WordPress) 分组的帖子的当前分类法

问题描述

我对 PHP 很蹩脚,但它写在星星上它会解决我的问题。 我在 wordpress 上发布了许多类别和子类别的帖子(只有两个级别:父级和直接子级)。

我需要做的是为每个帖子显示这个分层分类法。 我在这里找到了(对不起,我找不到回帖提及它)这段代码

$parent_terms = [];
$terms = get_terms( array( 
    'taxonomy' => 'annuaire_eta_dir_cat',// change to your taxonomy name
    'hide_empty' => false,) );

foreach( $terms as $term ) {
if( $term->parent == 0 ) {
    $parent_terms[] = $term;
}
};

// create level render

foreach( $parent_terms as $parent ) {
    $child_terms = get_terms( array( 
        'taxonomy' => 'annuaire_eta_dir_cat','child_of' => $parent->term_id,'hide_empty' => false,) );

        echo '<h4>' . $parent->name . '</h4>';
        echo '<ul>';
        foreach( $child_terms as $child ) {
        echo '<li>' . $child->name . '</li>';
        }

        unset($child_terms); // avoid garbage for reuse
        echo '</ul>';
}

但它显示了所有分类,而不仅仅是帖子的当前分类在这代码中,我找不到在何处以及如何放置 if 语句的条件。

我找到了这段代码,它完成了过滤工作:

function custom_taxonomies_terms_links() {
    global $post;
    // some custom taxonomies:
    $taxonomies = array( 
                         "annuaire_eta_dir_cat"=>"Secteurs et services : ",);
    $out = "<ul>";
    foreach ($taxonomies as $tax => $taxname) {     
        $out .= "<li>";
        $out .= $taxname;
        // get the terms related to post
        $terms = get_the_terms( $post->ID,$tax );
        if ( !empty( $terms ) ) {
            foreach ( $terms as $term )
                $out .= ''.$term->name.'<br>';

        }
        $out .= "</li>";
    }
    $out .= "</ul>";
    return $out;
} 

echo custom_taxonomies_terms_links();

但它不会对结果进行分组。 我尝试了很多来合并这两个代码,但正如我所说,我什至不确定我是否理解其中的一行代码

再次抱歉,我没有提到这些代码的作者......

有人能帮我解决这个问题吗?

提前谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)