Display custom taxonomy as dropdown list

I want to display list of custom taxonomies as a dropdown list.

I’ve found the solution here, @alexufo ‘s answer

Display a custom taxonomy as a dropdown on the edit posts page

But the problem with that is that when i publish the post with selected taxonomy it creates another taxonomy automatically.

I can’t comment on his answer as i don’t have 50 reputation.

here’s my code

function realty_type() {
    $args = array(
        'show_ui'                    => true,
        'meta_box_cb'                => 'drop_cat',
    );
    register_taxonomy( 'realty_type', array( 'my-CPT' ), $args );

    }

    // Hook into the 'init' action
    add_action( 'init', 'realty_type', 0 );


    function drop_cat( $post, $box ) {
    $defaults = array('taxonomy' => 'category');
    if ( !isset($box['args']) || !is_array($box['args']) )
        $args = array();
    else
        $args = $box['args'];
    extract( wp_parse_args($args, $defaults), EXTR_SKIP );
    $tax = get_taxonomy($taxonomy);
    ?>
    <div id="taxonomy-<?php echo $taxonomy; ?>" class="acf-taxonomy-field categorydiv">

            <?php 
            $name = ( $taxonomy == 'category' ) ? 'post_category' : 'tax_input[' . $taxonomy . ']';
            echo "<input type="hidden" name="{$name}[]" value="0" />"; // Allows for an empty term set to be sent. 0 is an invalid Term ID and will be ignored by empty() checks.
            ?>
            <? $term_obj = wp_get_object_terms($post->ID, $taxonomy ); //_log($term_obj[0]->term_id)?>
            <ul id="<?php echo $taxonomy; ?>checklist" data-wp-lists="list:<?php echo $taxonomy?>" class="categorychecklist form-no-clear">
                <?php //wp_terms_checklist($post->ID, array( 'taxonomy' => $taxonomy) ) ?>
            </ul>

            <?php wp_dropdown_categories( array( 'taxonomy' => $taxonomy, 'hide_empty' => 0, 'name' => "{$name}[]", 'selected' => $term_obj[0]->term_id, 'orderby' => 'name', 'hierarchical' => 0, 'show_option_none' => '&mdash;' ) ); ?>

    </div>
    <?php
    }

2 Answers
2

Below is the easiest solution I use for displaying custom taxonomy as the dropdown instead of checkboxes.

1/ Use third party WordPress plugin ‘ACF’ to create the taxonomy ‘Relational’ field type and display it as dropdown as shown in below screenshot.

Advanced Custom Fields (ACF)

enter image description here

enter image description here

For displaying taxonomy selected you can refer documentation of ACF for relational taxonomy field type.

Taxonomy

2/ Hide taxonomy checkbox by simply adding ‘meta_box_cb’ as ‘false’ when registering your custom taxonomy.

Hope this helps..!!

Leave a Comment