Dynamically Populate a Select field from Custom List

When we start using Custom Post Type & Custom Field to enrich our WordPress website, to meet various real world situation, building relationship between different datasets becomes a common practice. A simple example, is project & client relationship. If we manage this in database, we always link client to project using client ID, because client may repeat in multiple projects. If we use Custom Post Type to manage project and client in WordPress, the challenge is: how do we dynamically populate a latest client list into a client choices for a project?

In this real-world example, I use two custom post types to manage projects and clients data. To make the job simpler, Advanced Custom Fields (v4.3.8) is used to manage custom fields. I have a custom filed called client in Project CPT, and would like to populate the select list with latest client data from Client CPT.

To do so, I use acf_load_field filter provided by Advanced Custom Fields plugin. Here is the code:

function my_acf_load_field( $field )
{
	// Reset choices
	$field['choices'] = array();

	// Populate a blank option
	$field['choices'][''] = '';

	$args = array(
		'posts_per_page'   => -1,
		'orderby'          => 'post_title',
		'order'            => 'ASC',
		'post_type'        => 'client',
		'post_status'      => 'publish' );

	$clients = get_posts( $args );

	foreach ( $clients as $client ) {
		$choices[] = $client->post_title;
	}

	// loop through array and add to field 'choices'
	if( is_array($choices) )
	{
		foreach( $choices as $choice )
		{
			$field['choices'][ $choice ] = $choice;
		}
	}

    // Important: return the field
    return $field;
}

// v3.5.8.2 and below
// add_filter('acf_load_field-client', 'my_acf_load_field');

// v4.0.0 and above
add_filter('acf/load_field/name=client', 'my_acf_load_field');

 

 

Comments are closed.

Post Navigation