0

So Ive got this function here that creates a drop-down menu from only the child categories, it works great.

The problem is that I need to get the parent categories name and assign it as the value of the option class for the child category menus. I can't seem to get it to work, all I get is either '/' or '/child_Category_name/'

Thanks!

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

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




$categories = get_categories( $args );

$menu = '<select name="'.$dropID.'" id="'.$dropID.'" class="postform">';
$menu .='<option value="">--</option>';

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

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

}

3
  • Opps forgot to add what I've tried, Ive been trying to use get_category_parents() and get_category_parents($category).
    – Jon Furry
    Commented Nov 22, 2013 at 20:58
  • You need to pass the category ID; try get_category_parents( $category->id ), which returns a string of the parents, delimited by / by default. Commented Nov 22, 2013 at 21:30
  • Ahh ha! Thanks for pointing me in the right direction, I found that $category->parent_category returns the ID of the parent category. Which is easy enough to turn into the category name which is what I needed. Thanks!
    – Jon Furry
    Commented Nov 22, 2013 at 21:42

1 Answer 1

2

get_category_parents() requires the category ID to be passed as the first parameter, and returns an array a string of all the parents, separated by / by default. You can change this to a space to include them in your class list:

foreach ( $categories as $category ) {
    // Get the parents, separated by a space
    $parents = get_category_parents( $category->id, false, ' ' );

    // If $parents isn't an error, carry on
    if ( ! is_a( $parents, 'WP_Error' ) ) {
        $menu .= '<option class="' . $parents . '" value="' . $category->name . '">' . $category->name . '</option>';
    }
}

If you want to get all sorts of kooky, you can also print out your HTML like thus:

$menu .= sprintf( "<option class='%s' value='%s'>%s</option>",
                  esc_attr( $parents ),
                  esc_attr( $category->name ),
                  esc_attr__( $category->name )
         ); 
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.