首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在wordpress中获取父类别的名称

在wordpress中获取父类别的名称
EN

Stack Overflow用户
提问于 2012-10-21 11:27:03
回答 1查看 998关注 0票数 1

我有属于父类别(国家)的子类别(城市)。我得到一个类别列表(城市-国家),如下所示:

代码语言:javascript
复制
  $categor = $wpdb->get_results("select * from $wpdb->terms c,$wpdb->term_taxonomy tt  where tt.term_id=c.term_id and tt.taxonomy='hotelcategory' and c.name != 'Uncategorized' and c.name != 'Blog' $substr order by c.name");

for($i=0;$i<count($categor);$i++)
    {
 echo '"'.$categor[$i]->name.' - '.$categor[$i]->parent.'",';
    }

我在jquery自动完成中使用检索到的数据,并且我可以获得父类别id,但不能获得名称。

问题是,例如,有许多城市的名称为“巴黎”,所以当我在巴黎输入时,我得到的结果是8-9个城市具有相同的名称。(Picture1)我想做的是将它们的父类别名称放在类别旁边。(Picture2) http://s7.postimage.org/k85dhd4sr/catn.jpg

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-10-21 16:07:30

您只有父术语的ID,所以如果您想要术语的实际名称,您必须获取它。要做到这一点,一种方法是简单地再次连接parent ID的term表:

代码语言:javascript
复制
$categor = $wpdb->get_results( "select c.*,tt.*,pc.name as parent_name 
    from $wpdb->terms c,$wpdb->term_taxonomy tt,$wpdb->terms pc
    where
        tt.term_id=c.term_id and tt.parent=pc.term_id 
        and tt.taxonomy='hotelcategory' and c.name != 'Uncategorized' 
        and c.name != 'Blog' $substr order by c.name");

// I have optimized the loop a bit. If you really need the index you can leave
// it as it is. If you don't need the index I suggest you change that to a
// foreach loop
for($i=0,$n=count($categor);$i<$n;$i++)
{
    echo '"'.$categor[$i]->name.' - '.$categor[$i]->parent_name.'",<br />';
}

没有任何SQL的替代解决方案可能如下所示:

代码语言:javascript
复制
$excludes = array();

// build the "exclude" array. This step is necessary because
// get_terms expects the ID's of the terms to be excluded
foreach(array('Uncategorized', 'Blog') as $termName) {
    $term = get_term_by('name', $termName, 'hotelcategory');
    if($term) {
        $excludes[] = $term->term_id;
    }
}

$args = array(
    'hide_empty' => false,
    'exclude' => $excludes,
    'name__like' => 'Paris', // replace this with your search term here
);

$categor = get_terms('hotelcategory', $args);

foreach($categor as $cat)
{
    // look up the parent
    $parent = get_term_by('id', $cat->parent, $cat->taxonomy);
    echo '"'.$cat->name.' - '.($parent ? $parent->name : '-').'",<br />';
}

无可否认,这个解决方案有点冗长,但您不必担心SQL或数据库布局。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12994689

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档