0

I've created a select dropdown list of terms from a CPT taxonomy. This works fine. Here is my code

<label for="films">Films</label>
    <select name="films" id="films">
        <option value="" disabled selected>Films</option>
        <?php
            $taxonomy = 'films';
            $terms = get_terms($taxonomy); // Get all terms of a taxonomy

            if ( $terms && !is_wp_error( $terms ) ) : ?>
                <?php foreach ( $terms as $term ) { ?>
                    <option value="<?php echo get_term_link($term->slug, $taxonomy); ?>"><?php echo $term->name; ?></option>
                <?php } ?>
            <?php endif;?>
     </select>

What I'd like to do is when you select a term from the dropdown, it then jumps to the term archive page automatically. Similar to the native WP category dropdown widget.

1 Answer 1

0

I think you can achieve this by using JavaScript. You'll need to add an event listener that triggers a redirect to the selected URL when the dropdown's value is changed.

Here's one possible way of doing it. It's the quickest way I can think of, and I haven't tested it yet, but you get the idea. You can further improve on this by using jQuery if you want to.

<label for="films">Films</label>
<select name="films" id="films" onchange="document.location.href=this.options[this.selectedIndex].value;">
    <option value="" disabled selected>Films</option>
    <?php
        $taxonomy = 'films';
        $terms = get_terms($taxonomy); // Get all terms of a taxonomy

        if ( $terms && !is_wp_error( $terms ) ) : ?>
            <?php foreach ( $terms as $term ) { ?>
                <option value="<?php echo get_term_link($term->slug, $taxonomy); ?>"><?php echo $term->name; ?></option>
            <?php } ?>
        <?php endif;?>
</select>

Your Answer

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

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