繁体   English   中英

从当前帖子(自定义帖子类型)中获取子类别和父类别名称(自定义分类)

[英]Get child and parent category name (custom taxonomy) from current post (custom post type)

我正在尝试从当前帖子中获取父类别和子类别。
自定义帖子类型称为assortiment ,自定义分类称为assortiment-categorie

我们有一个名为SL524CB – 500kg的产品,其父类别Test和子类别( Testtest b

现在我做了一个输出子类别名称( test b )的循环,但我们还想要父类别名称( Test )。

对于 output 它们,我们需要 2 个变量,例如$parent_category$subcategory ,因此我们可以在模板中对它们进行 output。

这是我们现在使用的循环:

<?php 
    global $post;
    $terms = wp_get_object_terms( $post->ID, 'assortiment-categorie', array('fields'=>'names'));
    $term_id = array_pop( $terms ); //gets the last ID in the array
    echo $term_id;
?>

如果有人可以帮助我,那就太好了,已经感谢您的时间了!

我们可以通过多种方式实现这一目标。

@Chris Haas 评论是一种方法。 我,我更喜欢使用另一种方式。

关于父母,我们可以使用get_term_parents_list()来返回特定术语的父母。

使用分隔符检索术语父项。

<?php

$args = array(
    'format' => 'slug',
    'link' => false,
    'inclusive' => false,
);
  
$parents = explode( '/', get_term_parents_list( $term_id, $taxonomy, $args ) );

$î = 0;
foreach( $parents as $parent ) {
    $i++;

    echo $parent;

    if ( $i !== sizeof( $parents ) )
        echo ', ';

};

关于孩子,我们可以使用get_term_children()它将返回特定术语的孩子。

将所有术语子项合并到其 ID 的单个数组中。

<?php

$children = get_term_children( $term_id, $taxonomy );

$î = 0;
foreach( $children as $child ) {
    $i++;

    $term = get_term_by( 'id', $child, $taxonomy );

    echo $term->name;

    if ( $i !== sizeof( $children ) )
        echo ', ';

};

使用get_the_terms()

$categories = get_the_terms( get_the_ID(), 'category' );
echo "<pre>"; print_r($categories); echo "</pre>"; 

如果您打印$categories那么您将有一个 output 如下所示。 您可以在其中确定$termparentchild

Array
(
    [0] => WP_Term Object
        (
            [term_id] => 18
            [name] => Test 2
            [slug] => test-2
            [term_group] => 0
            [term_taxonomy_id] => 18
            [taxonomy] => category
            [description] => 
            [parent] => 17
            [count] => 1
            [filter] => raw
        )

    [1] => WP_Term Object
        (
            [term_id] => 17
            [name] => Test
            [slug] => test
            [term_group] => 0
            [term_taxonomy_id] => 17
            [taxonomy] => category
            [description] => 
            [parent] => 0
            [count] => 1
            [filter] => raw
        )

)

试试下面的代码。

foreach ( $categories as $key => $category ) {
    if( $category->parent == 0 ){
        echo "Parent => ".$category->name;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM