Meta box dropdown of custom posts

I am trying to display a dropdown select metabox on the “add new” page of a custom post type which displays a drop down list of titles from a separate custom post type ( it’s an effort to relate the two CPT’s together – one being “clients” and the other being “projects” so that when creating a new project one would be required to select a client from the drop down select ).

All works well except for the fact that somehow the query is affecting WordPress because when i click “add new project” instead of an empty field for the title like you’d normally get it is populated instead with the title of the first CLIENT. I thought that by adding wp_reset_postdata() that it would solve the problem but it didn’t. Can anyone help? ( I am only adding what i think is the relevant/problematic piece of code as the metabox code itself works as expected as far as i can see and i assume the problem is with the way i’ve done the query)

  <select name="my_meta_box_select" id="my_meta_box_select">
  <?php 
  $my_loop = new WP_Query( array( 'post_type' => 'clients', 'posts_per_page' => 10 ) );
  while ( $my_loop->have_posts() ) : $my_loop->the_post();
  $title = get_the_title();
  ?>
  <option value="<?php echo $title ?>" <?php selected( $selected, $title ); ?>><?php echo $title ?></option>
  <?php
  endwhile;
  ?>            
  </select>

  <?php
  wp_reset_postdata();
  }

Related posts

Leave a Reply

2 comments

  1. What I would do is just create a custom taxonomy type to share between both custom post types that are dynamically created when a new post of the Clients type is created with the same title, then you can associate them without any custom meta handling.