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’


   $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 acf/load_field 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:ACF | Dynamically populate a select field’s choicesNeed to dynamically populate a field’s choices? This tutorial will cover how to take a value saved to the options page…www.advancedcustomfields.comget_post_types() can’t get some of my post typeThanks for contributing an answer to WordPress Development Stack Exchange! Please be sure to answer the question…wordpress.stackexchange.com

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

Leave a Reply