php - 获取父+子 WordPress 分类名称/Slugs

标签 php wordpress custom-taxonomy

我遇到了一个小问题...ლ(ಠ益ಠლ) 我正在寻找以分层形式获取父+子名称(或别名)...但仅限于我的帖子中选定的名称。

例如:

> New York (parent)
> -Rome
> -Middletown
> -Mount Vernon * (selected in post)
> -New York

> California (parent)
> -Auburn
> -Dublin

所以我想收到:

New York
Mount Vernon

如果可能的话,我想选择 NAME 而不是 SLUGS(因为我的城市有 2 个或更多名称,并且会有很多破折号 -)。

我试图使用 get_the_terms,但它只返回子名称,没有父名称。在数组中,它仅显示父 ID,没有父名称。

我的分类是:特性-城市

它有城市和社区的名称。

知道如何解决这个问题吗?

此外,我需要使用 get_the_id() 而不是 $Post->ID,我不知道这是否是一个问题,因为我没有得到好的结果... ᕙ(⇀‸↼‶)ᕗ

哦!它不需要全部在一串中。如果我只能选择一个(城市或社区,而不是城市和社区),那就更好了。 ᕕ( ᐛ )ᕗ

最佳答案

尝试这样:

$post_id = get_the_ID();

// get the assigned taxonomy terms for "property-city"
$assigned_terms = wp_get_post_terms($post_id, 'property-city', array("fields" => "all"));

// loop through the term objects
foreach($assigned_terms as $term){

    // display child term name
    echo 'Child term:'.$term->name.'<br>';

    // display parent term name
    if($term->parent != 0){
        $parent = get_term_by( 'id', $term->parent , 'property-city' );
        echo 'Parent term:'.$parent->name.'<br>';
    }
}

关于php - 获取父+子 WordPress 分类名称/Slugs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32208615/

相关文章:

css - 如何将 wp 模板链接到不同的样式表

css - Wordpress: Logo 在小屏幕上的尺寸非常小

php - 获取 Woocommerce 单一产品页面中的产品类别名称和描述

php - 为 doctrine2 查询添加所有相关项的计数

php - 从每个定义中读取名称和值 ('NAME' ,'VALUE' );在 .php 文件中

php - 将变量的值添加到数据库字段

php - 移动导航栏 Wordpress 神秘主题问题

php - 在自定义主页和产品类别文件中显示 WooCommerce 产品属性

php - 更新 PHP 和 MySQL 服务器实例