简体   繁体   中英

How to get custom taxonomy parent category name from ID?

This function creates a select menu from a custom taxonomies child categories only.

function cityDropdown($dropID, $taxonomy, $exclude) {

    $catArgs = array(
    'orderby'                  => 'name',
    'order'                    => 'ASC',
    'hide_empty'               => 0,
    'hierarchical'             => 1,
    'exclude'                  => $exclude,
    'taxonomy'                 => $taxonomy,
    'pad_counts'               => false );




    $categories = get_categories( $catArgs );

    $menu = '<select name="cityDropdown" id="'.$dropID.'">';
    $menu .= '<option value="">(City)</option>';

    foreach($categories as $category)
    {


        if($category->parent != 0 ) {

            $parent = $category->category_parent;

            $menu .= '<option class="'.$parent.'" value="'.$category->name.'" name="'.$category->name.'">'.$category->name.'</option>';
        }
    }   
    $menu .= '</select>';
    echo $menu;

}

It works fine, except for one thing:

$parent = $category->category_parent;

gives me the ID of the parent category, which is cool and all and it works for what I need to do, but, it would be so much better if it could give me the name of the parent category instead of the ID.

I tried single_term_title($parent) that didn't do anything, I also tried single_cat_title($parent) but that also returns blank.

Try $parent_term = get_term($parent,'category') . And then $parent_term->name , although if you were to base a class off of a term, I'd use $parent_term->slug , since ->name could give you spaces and that is undesirable for a CSS class name but you really can't give option tags a class ( see below ).

Extra:

<option> tags do not really have a name attribute according to http://www.w3schools.com/tags/tag_option.asp . You may want to give it an id instead of name .

Also, when I do dynamically generated options, I try to think of the value attribute as an id I'd want to use as an array index or variable name so I like to make sure it's either an integer or a reliable space-less textual id. For WP taxonomies, I'd suggest using $category->term_id or $category->slug for the value and of course as you have $category->name for the inner html.

You're almost there. To return the full array of data for a custom taxonomy term, try:

$parent = get_term( $category->category_parent, $taxonomy );

Now, you'll have access to the term array, which includes $parent->name , $parent->slug , and $parent->description .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM