Dynamically populate a select field’s choices for Custom Post Types— ACF

Adding the dynamic select field choices in Advanced Custom Fields can be challenging, as ACF does not offer this feature by default. In this blog, we will discuss to do just that.

Register a custom field with name ‘post_type_selection’ and field type ‘Select’

namespace YouNameSpace;function load_post_type_choices( $field ) {

$choices = [];
$post_types = get_post_types( [
'public' => true,
'show_ui' => true,
] );
$post_types_to_exclude = [ 'attachment', 'page' ];

foreach ( $post_types as $post_type => $slug ) {
if ( ! in_array( $slug, $post_types_to_exclude, true ) ) {
$choices[ $slug ] = ucfirst( $post_type );
}
}

$field['choices'] = $choices;
$field['default_value'] = 'post';

return $field;
}

add_filter( 'acf/load_field/name=post_type_selection', __NAMESPACE__ . '\\load_post_type_choices' );

Now let’s write the PHP code as described above. Notice that, we have added our field name in the hook as `acf/load_field/name=post_type_selection`

Now we can see post types in the dropdown.

That’s all folks.

More useful references:

https://www.rarst.net/images/wordpress_core_load.png

👤 Full Stack Developer at rtCamp, Speaker, Blogger, YouTuber, Wordpress, React, Node, Laravel Developer http://youtube.com/ImranSayedDev