Suppose you have two select fields with titles 'Field 1 Title' and 'Field 2 Title' and both need to have options from the post type with slug, 'country'.
The code in this case will look like this:
add_filter( 'wpt_field_options', 'fill_custom_field_options', 10, 3);
function fill_custom_field_options( $options, $title, $type ){
switch( $title ){
case 'Field 1 Title':
case 'Field 2 Title':
$args = array(
'post_type' => 'country',
'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;
}
And for the case, where your custom fields, need to have options from two different post types, you can use two separate functions:
add_filter( 'wpt_field_options', 'fill_custom_field_1_options', 10, 3);
function fill_custom_field_1_options( $options, $title, $type ){
switch( $title ){
case 'Field 1 Title':
$args = array(
'post_type' => 'country',
'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;
}
add_filter( 'wpt_field_options', 'fill_custom_field_2_options', 10, 3);
function fill_custom_field_2_options( $options, $title, $type ){
switch( $title ){
case 'Field 2 Title':
$args = array(
'post_type' => 'city',
'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;
}
In these two functions, the first one will set options from the 'country' post type for the field with the title 'Field 1 Title'. And the second one will set options from the 'city' post type, for the field with the title 'Field 2 Title'.
I hope these examples will make the usage more clear and for more personalized assistance around custom code, you can also consider hiring a professional from our list of recommended contractors:
https://toolset.com/contractors/