php
  • wordpress
  • 2012-10-21 203 views 1 likes 
    1

    我有属于父类别(国家)的子类别(城市)。我得到类别(城市,国家)的列表如下:获取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

    回答

    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或数据库布局。

    +0

    很酷,它的作品谢谢。我刚接下第一个解决方案。 – user1762496

    相关问题