我有子类别(城市)属于父类别(国家/地区)。我得到一个类别(城市 - 国家)列表如下:
$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个同名的城市。(图1) 我想做的是在类别旁边有他们的父类别名称。(图2) http://s7.postimage.org/k85dhd4sr/catn.jpg
答案 0 :(得分:0)
您只需拥有父条款的ID,因此如果您想要获取该条款的实际名称,则必须获取该条款。一种方法是再次为parent
ID加入术语表:
$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的替代解决方案可能如下所示:
$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或数据库布局。