Skip Navigation

[Resolved] CPT call field in a second CPT

This support ticket is created 3 years 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)

Author
Posts
#2207041

Hi,
Is it possible to load the records of a CPT (example Model) in a drop-down menu of a second CPT (example car)?
I would like that by creating a car I can select the various models entered from a drop-down menu.

Thanks

#2207723

Hi,

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

If you'd like to offer the ability to search the "Car" CPT posts through their "Models" using views on the front-end, then it would be better to add "Models" as custom taxonomy and not as a CPT.

In case, you don't need to search cars by models, then you can use the "wpt_field_options" filter, to dynamically generate the options for a select type custom field, from another CPT.
( ref: https://toolset.com/documentation/programmer-reference/types-api-filters/#wpt_field_options )

For example, suppose, your "Cars" CPT has a select type custom field with the title "Car Model". This field doesn't need to have any options defined in the field's settings, as we'll generate them programmatically.

The code, in this case, would look like this:


add_filter( 'wpt_field_options', 'func_to_dynamically_populate_car_models, 10, 3);
function func_to_dynamically_populate_car_models( $options, $title, $type ){
    switch( $title ){
        case 'Car Model':
            $options = array();
  
            // add first empty value
            $options[] = array('#value' => '', '#title' => '---');
  
            // get all "Models" post items
            $args = array( 'post_type' => 'model-cpt-slug', 'posts_per_page' => -1, 'post_status' => 'publish','orderby' => 'title' );
  
            $results = get_posts( $args );
            if ( $results ) {
                foreach ( $results as $post ) {
                    $options[] = array('#value' => $post->ID, '#title' => $post->post_title);
                }
            }
  
        break;
    }
    return $options;
}

Note: Please replace "Car Model" and "model-cpt-slug" with your actual custom field and post type slugs, respectively.

The above code snippet can be included through either Toolset's custom code feature ( ref: https://toolset.com/documentation/adding-custom-code/using-toolset-to-add-custom-code/ ) or through the active theme's "functions.php" file.

I hope this helps and please let me know if you need any further assistance around this.

regards,
Waqar