I have been working on a plugin that uses text area metaboxes on an options page to populate drop downs in the CPT area. I was with the help of some others able to get the list to show in the select boxes and was able to save the choice to the DB. So far I have been unsuccessful at showing the selected item in the CPT area. Is there an easier way of accomplishing a user editable select box? Or can someone explain why selected is not functioning in this code? I have used var_dump() to verify the variables return the expected outcome. It is like the selected statement is ignored. See code below:

        $post_id = $post->ID;
        $options = get_option( 'name' );
        $names = explode( PHP_EOL, $options );
        $name_value = get_post_meta( $post_id, 'name', true );
        echo '<pre>'; var_dump($name_value); echo '</pre>';
        <label for="name" class="timeshare-row-title"><?php _e( 'Property Name:', 'timeshare-textdomain' )?></label>
        <select name="name" id="name">
        <?php foreach ( $names as $name ) {

                 '<option value="%s" %s>%s</option>',  
            selected($name, trim( $name_value ), false),

        } ?>


Select Box with var_dump()

  • Are you sure that the name_value and name are equal with same capital and small letter etc – WPTC-Troop Nov 18 '15 at 19:14
  • @WPTC-Troop Added an image so you could see the admin portion. In answer to your question yes they do match up. – John Lucey Nov 18 '15 at 19:29

Seems like $name_value dump is 10 characters long although Michelle is only 8 characters long. Try adding trim( $name_value ) to selected function.

  • @ville6000-I see what you mean, never even clicked in my head that would have an effect. I added trim as you said, you can see the code above I updated it. But it does not appear to be working. – John Lucey Nov 18 '15 at 20:04
  • Try adding trim to $name also – ville6000 Nov 18 '15 at 20:10
  • @Ville6000-It appears this did the trick, I am going to do more testing to be sure but I think that got it. – John Lucey Nov 18 '15 at 20:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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