Skip Navigation

[Resolved] Programmatically add options to select custom field with a filter

This support ticket is created 2 years, 8 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Karachi (GMT+05:00)

This topic contains 1 reply, has 2 voices.

Last updated by Waqar 2 years, 8 months ago.

Assisted by: Waqar.

Author
Posts
#2319955

Tell us what you are trying to do?
I have a custom field select type on a User and would like to list all of the posts as options in that select field from a custom post type (key: id, value: title), basically to create a link between the user and an associated custom post.

Is there any documentation that you are following?
https://toolset.com/forums/topic/linking-dropdown-in-custom-post-field-to-user-id/ - is this still applicable to the latest versions? I just can't seem to get anything to happen through that filter hook 'option_wpcf-fields'.

[code]
add_filter('option_wpcf-fields', 'fill_our_people');
function fill_our_people($fields) {
foreach ($fields as &$field) {
if ($field['id'] == 'team-member-associated') {
$field["data"]["options"] = array();
$args = array(
'post_type' => 'team-member'
);

$our_people = get_posts( $args );
foreach ($our_people as $team_member) {
$key = $field["id"] . $team_member->post_title;
$field["data"]["options"][$key] = array(
"title" => $team_member->post_title,
"value" => $team_member->ID
);
}
}
}
return $fields;
}
[/code]

#2320285

Hi,

Thank you for contacting us and I'd be happy to assist.

The filter "option_wpcf-fields" works for the post custom fields, but not for the user custom fields.

You can update your code to use the "wpt_field_options" filter, which works for both types of custom fields:
https://toolset.com/documentation/programmer-reference/types-api-filters/#wpt_field_options

Example:


add_filter( 'wpt_field_options', 'fill_our_people', 10, 3);
function fill_our_people( $options, $title, $type ){
	switch( $title ){
		case 'Team Member Associated':
			$args = array(
				'post_type'        => 'team-member',
				'posts_per_page'   => -1,
				'post_status'      => 'publish',
			);
			$posts_array = get_posts( $args );
			foreach ($posts_array as $post) {
				$options[] = array(
					'#value' => $post->ID,
					'#title' => $post->post_title,
				);
			}             
		break;
	}
	return $options;
}

Note: Please make sure that the 'Team Member Associated' is replaced with the exact 'Field name' (and not the 'Field slug') of your user field.

regards,
Waqar