0

I'm creating a series of select drop down menus that pull data from various taxonomies. I got this PHP script working for a WooCommerce attribute of color:

function get_color_dropdown($taxonomies, $args){
    $myterms = get_terms($taxonomies, $args);
    $output ="<select onChange='window.location.href=this.value'>";
    foreach($myterms as $term){
        $root_url = get_bloginfo('url');
        $term_taxonomy=$term->taxonomy;
        $term_slug=$term->slug;
        $term_name =$term->name;
        $link = $root_url.'/'.$term_taxonomy.'/'.$term_slug;
        $output .="<option value='".$link."'>".$term_name."</option>";
    }
     $output .="</select>";
return $output;
}

$taxonomies = array('pa_color');
$args = array('orderby'=>'name','order'=>'ASC','hide_empty'=>true);
echo get_color_dropdown($taxonomies, $args);

Great. This is what I want. But it's missing something. A default value.

In my case, I want it to be something that doesn't even appear in the database. Something like 'Shop by Color -->' since if it just has the first value, nobody is going to know what it is and what to do. No good.

So is there some kind of statement I can incorporate to add this one line of code to my select menu?

1 Answer 1

1

Simply add an extra line before your for loop. For example:

function get_color_dropdown($taxonomies, $args){
    $myterms = get_terms($taxonomies, $args);
    $output ="<select onChange='window.location.href=this.value'>";
    $output .= "<option value='default'>Shop by Color --></option>";
    foreach($myterms as $term){
        $root_url = get_bloginfo('url');
        $term_taxonomy=$term->taxonomy;
        $term_slug=$term->slug;
        $term_name =$term->name;
        $link = $root_url.'/'.$term_taxonomy.'/'.$term_slug;
        $output .="<option value='".$link."'>".$term_name."</option>";
    }
    $output .="</select>"; return $output;
}

$taxonomies = array('pa_color');
$args = array('orderby'=>'name','order'=>'ASC','hide_empty'=>true);
echo get_color_dropdown($taxonomies, $args);

You can always check to see if the return value is "default" to see if the select wasn't set.

1
  • That's it. I thought it might be something along those lines, but I just wasn't sure. Thanks. Commented Feb 17, 2015 at 2:04

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.