簡體   English   中英

在WordPress中獲取父類別的名稱

[英]Getting the name of the parent category in wordpress

我有屬於父類別(國家)的子類別(城市)。 我得到以下類別(城市國家)的列表:

  $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

您僅具有父項的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或數據庫布局。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM