Custom Field Select Box (Adding Select Keyword)

I have added a couple of custom fields to my WordPress posts, for a theme I am creating for my hobby (cars). I am having trouble with selecting an Option from an HTML select box. If I select it, it works and save correctly ~ displaying the correct value on the front end, but when I return to the post page, it always shows the first value of the options, and not the chosen one. For example, if I select Automatic, it will show on the front end, but when I revisit the backend it is Manual again.

I know that to get it to stick to the selected post, I have to add the selected keyword to the choice, but this is where I am having problems.

Read More

What I’ve done

What I have done so far is work from this tutorial: http://wpshed.com/create-custom-meta-box-easy-way/

I created a select box like so:

function wpshed_meta_box_output( $post ) {
  // create a nonce field
  wp_nonce_field( 'my_wpshed_meta_box_nonce', 'wpshed_meta_box_nonce' ); ?>

    <p>
        <label for="transmission_textfield"><?php _e( 'Transmition', 'wpshed' ); ?>:</label>
        <!-- <input type="text"  value="<?php echo wpshed_get_custom_field( 'transmission_textfield' ); ?>" /> -->

        <select name="transmission_textfield" id="transmission_textfield">
          <option value="Manual" >Manual</option>
          <option value="Automatic">Automatic</option>
        </select>

        </p>
    }

    function wpshed_meta_box_save( $post_id ) {
      if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

      if( isset( $_POST['transmission_textfield'] ) )
        update_post_meta( $post_id, 'transmission_textfield', esc_attr( $_POST['transmission_textfield'] ) );


    }
    add_action( 'save_post', 'wpshed_meta_box_save' );

?>

How can I add the selected keyword to the option chosen?

Related posts

1 comment

  1. You need to set the selected property manually on the <option> – ie. get the value and then use the wordpress function selected() to output the property in the relevant place like this:

    <?php
    $selected_option = get_post_meta($post->ID, 'transmission_textfield', true);
    ?>
    <select name="transmission_textfield" id="transmission_textfield">
        <option value="Manual" <?php selected($selected_option, 'Manual') ?>>Manual</option>
        <option value="Automatic" <?php selected($selected_option, 'Automatic') ?>>Automatic</option>
    </select>
    

    You don’t post the code for wpshed_get_custom_field(), so I won’t use it, but I’m guessing it’s just a wrapper for get_post_meta()… in which case you can go ahead and use that instead…

Comments are closed.