How to store the value of a custom field dropdown select for post referencing?

selected() was big help for setting a default value. The rest I found in this brilliant meta box tutorial: http://code.tutsplus.com/tutorials/how-to-create-custom-wordpress-writemeta-boxes–wp-20336 with examples for text input, checkboxes and dropdown. Also Custom post type’s slug gets wrong when adding a custom meta box explained me how to correctly handle the current post object so it doesn’t get mixed up with the options objects.

/*** callback ***/
function meta_options(){
  global $post;
  // storing the global post object so it doesn't get mixed up with the options
  $post_old = $post

  $custom = get_post_custom($post->ID);
  if (isset($custom["reference_id"][0])) {
    $reference_id = $custom["reference_id"][0];
  } else {
    $reference_id = '0';
  }
  ?>
    <form action="<?php bloginfo('url'); ?>" method="get">
      <select name="ref_id" id="ref_id">
        <option value="0" <?php selected($reference_id, '0'); ?>>- choose client -</option>
      <?php
      global $post;
      $args = array(
        'numberposts' => -1,
        'post_type' => 'page',
        'post_parent' => 21
        );
      $posts = get_posts($args);
      foreach( $posts as $post ) : setup_postdata($post); ?>
        <option value="<?php echo $post->ID; ?>" <?php selected($reference_id, $post->ID); ?>><?php the_title(); ?></option>
      <?php endforeach; ?>
      </select>
    </form>
  <?php
  // restoring the global post object
  $post = $post_old;
  setup_postdata( $post );
}

/*** save_post ***/
function save_reference_id(){
  global $post;
  if (isset($_POST["ref_id"])) {
    update_post_meta($post->ID, "reference_id", $_POST["ref_id"]);
  }
}

Leave a Comment