向父母展示分类法孩子

时间:2018-10-16 22:17:13

标签: php wordpress

我将分类法配置为分层类别,碰巧当我创建一个帖子并选择父级和子级类别时,当我首先给出父级时,请遵循我使用的代码,以获得更好的解释:

<?ph

    $local = get_the_terms($post->ID, 'fornecedor_localidade');

    $parent_id = $local[0]->parent;
    $parent = get_term_by( 'id', $parent_id, 'fornecedor_localidade' );

    echo $local[0]->name. '/' .$parent->slug;

?>

今天看起来像这样:

父母/孩子

我希望它看起来像这样:

孩子/父母

我不知道Wordpress会解释哪种系统来对类别进行排序,但是我尝试了所有操作,但不能,我在等待一些帮助。

1 个答案:

答案 0 :(得分:1)

简单的方法,反转get_the_terms结果。

https://developer.wordpress.org/reference/functions/get_the_terms/

$local = get_the_terms($post->ID, 'fornecedor_localidade');
if ($local && !is_wp_error($local)) {
    $local = clone (object)array_reverse((array)$local);
    $local_names = array();
    foreach ($local as $term)
        $local_names[] = $term->name;
    $locals = implode(" / ", $local_names);
    echo $locals;
}

另一种方式:

$local = get_the_terms($post->ID, 'fornecedor_localidade');
if ($local && !is_wp_error($local)) {
    $local_names = array();
    foreach ($local as $term)
        $local_names[$term->term_id] = $term->parent==0 ? $term->slug : $term->name;
    ksort($local_names);
    $locals = implode(" / ", array_reverse($local_names));
    echo $locals;
}