Create drop down with all wordpress custom post types


<?php
    //GET ONLY PUBLIC CUSTOM POST TYPES CREATED BY THEME & HIDE THE DEFAULT POST TYPES
    $args=array(
      'public'   => true,
      '_builtin' => false
    );
   
    //ASSIGN THAT TO A VARIABLE
    $post_types = get_post_types($args,'name');
?>

<select class="go_to_select neue_thin" onchange="window.open(this.options[this.selectedIndex].value,'_self')">
   
    <?php
        //onchange="window.open(this.options[this.selectedIndex].value,'_self')"
        // THE ABOVE CODE REDIRECTS BROWSER TO THE SELECTED OPTION FROM THE 'SELECT' Drop Down.
    ?>
   
    <?php foreach ($post_types as $post_type ) { ?>
        <?php
            $selected = "";
           
            //IF THE POST TYPE IN THE LOOP IS SAME AS POST TYPE OF THE PAGE APPLY SELECTED ATTRIBUTE.
            if ( $post_type->rewrite[slug] == get_post_type() )  {
                $selected ="selected= 'selected'";
            }
        ?>
        <option value="<?php echo home_url( '/' ).$post_type->rewrite[slug]; ?>" <?php echo $selected; ?>><?php echo $post_type->labels->name; ?></option>
    <?php } ?>
</select>

Latest Comments

Leave a Reply

comment on this article