I'm building an employee website for a company that has many "sub companies". I need to add a dropdown to the user registration that will enable either the user (or later the admin of the sub company) to select the sub company the user works for. I cannot create a child relationship between the user and the company post type as the user type is a wordpress type.
There is a PHP filter, wpt_field_options, that can be used to dynamically modify a select field's options.
So, go ahead and create a user custom field which will store the sub-company name on their profile. It needs to be a select box, and you should add a couple of dummy options to act as placeholders, it doesn't matter what they are as they will be replaced.
Now add the following custom code (which you can do at Toolset > Settings > Custom Code):
/**
* Filter User Field
*/
function tssupp_filter_user_field_options($options, $title, $type) {
if ($title == 'Linked project') { // Edit for the name of your custom user field
// only keep the existing first, empty, option
$options = array($options[0]);
// get the posts to populate dropdown options
$posts = get_posts(
array(
'post_type' => 'project', // Edit the slug of the post type to populate the dropdown with
'nopaging' => true,
'post_status' => 'publish',
)
);
foreach ($posts as $key => $post) {
$options[] = array(
'#value' => $post->ID,
'#title' => $post->post_title,
);
}
}
return $options;
}
add_filter('wpt_field_options', 'tssupp_filter_user_field_options', 10, 3);
Note that you will need to make a few edits, specifically the name of your custom user field, and the slug of the post type which should be used to generate the options.
Note that I save the post ID as the option value, and the post title as the display value.