Skip to content

Instantly share code, notes, and snippets.

@magnificode
Last active August 29, 2015 14:26
Show Gist options
  • Save magnificode/fb91b4716fa1fabcdd8e to your computer and use it in GitHub Desktop.
Save magnificode/fb91b4716fa1fabcdd8e to your computer and use it in GitHub Desktop.
Dynamic Advanced Custom Fields public custom post type select field.
<?php
/*
* Add this snippet to your functions.php file
* Create a select field through ACF (can be used in flexible content, repeater, etc.)
* Leave the choices field blank in the ACF backend
* Add it to your page.
*/
function acf_load_cpt_field_choices( $field ) {
// Reset choices
$field['choices'] = array();
//Get only public custom post typoes
$args = array(
'public' => true,
'_builtin' => false
);
$output = 'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
$choices = get_post_types( $args, $output, $operator );
// loop through array and add to field 'choices'
if( is_array($choices) ) {
foreach( $choices as $choice ) {
$field['choices'][ $choice ] = $choice;
}
}
// return the field
return $field;
}
//Ensure the name is the name of the select field you want populated.
add_filter('acf/load_field/name=cpt_select', 'acf_load_cpt_field_choices');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment