0

I am using the following function to create a dropdown search form and populate it with the terms of a custom taxonomy called 'grades'. The dropdown works for searching, but I can't figure out how to add the selected class to the selected term. See the variable in my function below $SEARCHEDTERM -- how can I get that to equal the searched term?

function get_terms_grades_dropdown() {

    $myterms = get_terms('grades');
    $output = "";
    foreach ($myterms as $term) {     
        $term_taxonomy = $term->taxonomy;
        $term_slug = $term->slug;
        $term_name = $term->name;
        $value = $term->term_id;
        if ($SEARCHEDTERM == $term->slug) {
            $selected = "selected='selected'";
        } else {
            $selected = '';
        }
        $output .= "<option value='" . $value . "' " . $selected . ">" . $term_name . "</option>";
    }

    return $output;
}
5
  • Have you passed term name in URL as parameter or anything? Apr 21, 2015 at 4:01
  • No, there's nothing added to the URL.
    – LBF
    Apr 21, 2015 at 4:10
  • Ok, then may be you have passed through POST method. First get selected term ID from $_POST and find its slug. You can use this get_term_by. After that compare that slug like you are currently comparing. Apr 21, 2015 at 4:19
  • I did a var dump of $_POST and after I searched I got this: array(7) { ["action"]=> string(13) "search_events" ["category"]=> string(2) "-1" ["grade"]=> string(1) "7" ["centercat"]=> string(0) "" ["country"]=> string(1) "0" ["near_distance"]=> string(2) "25" ["near_unit"]=> string(2) "mi" }
    – LBF
    Apr 21, 2015 at 4:48
  • A var dump of $POST['grade'] = string(1) "7" -- how I can get that in a usable format for the comparison?
    – LBF
    Apr 21, 2015 at 4:51

1 Answer 1

0

To show dropdown with currently selected option, first you need to fetch current value. You can get that value from $_REQUEST variable. If you have grade variable then your current value is $_REQUEST['grade'].

Eg. if ($_REQUEST['grade'] == $term->slug)

Recommended:
Do not use REQUEST variable directly without sanitization. Use function like esc_attr. If you are sure that you need positive integer, you can use absint. May be.

$current_grade = esc_attr( $_REQUEST['grade'] );
if ($_REQUEST['grade'] == $term->slug)
1
  • Thank you. Can you tell me why I should use $_REQUEST['grade'] instead of $_POST['grade']?
    – LBF
    Apr 21, 2015 at 14:33

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.