WordPress: Create a dropdown list with Custom Post Type

Photo by Alesia Kazantceva on Unsplash

WordPress: Create a dropdown list with Custom Post Type

work with function.php

Yuki R.'s photo
Yuki R.
·Aug 10, 2022·

1 min read

Custom post type => Comparison

Each post has a compare item name as a title.

You want to create a compare item dropdown list. Here you can do it like this.

function.php

<?php 

    $compare = 101; //ID of default item that show up as selected
    $nolist=100; //ID that you want to remove from the dropdown list

    $choose = new WP_Query( array(
        'posts_per_page'=>-1, //Show all
        'post_type'=>'comparison',
        'post__not_in' => array($nolist), // don't include in dropdown
        'orderby' => 'title', //date is available
        'order' => 'ASC'
    ) ); 

    if ( $choose->have_posts() ) : //build comparison selector
    $chooser = "<select name='compare' id='compare'>";                
        while ($choose->have_posts()) : $choose->the_post(); 
            $comp_id = get_the_ID();
            $comp_name = get_the_title();
            if($comp_id == $compare) :
                $chooser .= "<option value='".$comp_id."' selected='selected'>".$comp_name."</option>";
            else :
                $chooser .= "<option value='".$comp_id."'>".$comp_name."</option>";
            endif;
        endwhile;
    $chooser .="</select>";

    endif; 

    wp_reset_postdata(); //reset

?>

Insert to a page template

<?php echo $chooser; ?>
 
Share this