我有属于父类别(国家)的子类别(城市)。我得到一个类别列表(城市-国家),如下所示:
$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
发布于 2012-10-21 16:07:30
您只有父术语的ID,所以如果您想要术语的实际名称,您必须获取它。要做到这一点,一种方法是简单地再次连接parent ID的term表:
$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或数据库布局。
https://stackoverflow.com/questions/12994689
复制相似问题