Getting the name of the parent category in wordpress

I have child categories (cities) which belongs to parent categories (countries). I get a list of categories (cities-countries) as below:

  $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.'",';
    }

I use the retrieved data in jquery autocomplete, and i can get the parent category id but not the name.

Read More

The problem is for example there are many cities named “Paris”, so when i type in paris, i get like 8-9 cities with same name.(Picture1)
What i’d like to do is to have their parent category names beside the category.(Picture2)
http://s7.postimage.org/k85dhd4sr/catn.jpg

Related posts

Leave a Reply

1 comment

  1. You just have the ID of the parent-term, so if you want the actual name of the term you have to fetch it. One way to do that is to simply join the term table again for the 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 />';
    }
    

    An alternative solution without any SQL could look like that:

    $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 />';
    }
    

    This solution is admittedly a bit more verbose, but you don’t have to worry with SQL or the database layout.