I am in the middle of a project to create a new event management system. One of the requirements is to relate events to participating staff; those staff members will have a different role depending on the event. While the relationship part is fairly straightforward (Events and Participants are CPTs), the role solution eluded me for a while. After asking in the Facebook group, my solution is to create a cloneable group with the staff member’s name and a role drop-down. I didn’t want to duplicate information but to use the participant information I already had (CPT).

The Query

Being fairly inexperienced with writing WordPress queries (I am trying), I turned to ChatGPT, gave it a prompt, and in a matter of seconds it gave me a usable query complete with comments.

PHP
function custom_get_speakers() {
    $speakers = get_posts( array(
        'post_type'      => 'speakers',
        'posts_per_page' => -1, // Retrieve all speakers
        'orderby'        => 'meta_value',
        'meta_key'       => 'last_name', // Replace 'last_name' with your custom field name for the last name
        'order'          => 'ASC', // Sort in ascending order
    ) );

    $speaker_options = array();

    foreach ( $speakers as $speaker ) {
        $speaker_id = $speaker->ID;
        $first_name = get_post_meta( $speaker_id, 'first_name', true ); // Replace 'first_name' with your custom field name for the first name
        $last_name  = get_post_meta( $speaker_id, 'last_name', true );  // Replace 'last_name' with your custom field name for the last name

        if ( $first_name && $last_name ) {
            $speaker_options[ $speaker_id ] = $first_name . ' ' . $last_name;
        }
    }

    return $speaker_options;
}

I have some additional testing to complete to make sure the values are what I need. Once the testing is done, I will finalize the single template and publish another article to outline the entire process.

Dynamic Select

Once you have a query available, adding it to the select is just a matter of adding the function name. I opted to use the Advanced Select because, eventually, this list will have 40-50 entries, and I wanted it to be searchable.

Screenshot of the Meta Box interface