Fill an ACF Select Field With Posts of a Type
Loads the choices of an ACF select field from the titles of a post type, such as locations or team members, and refreshes them when those posts change.
Opens WPIDE on
Code
// Select field name and the post type supplying its choices.
$wpide_acf_choice_field = 'location';
$wpide_acf_choice_type = 'page';
add_filter( 'acf/load_field/name=' . $wpide_acf_choice_field, function ( $field ) use ( $wpide_acf_choice_type ) {
$key = 'wpide_acf_choices_' . $wpide_acf_choice_type;
$choices = get_transient( $key );
if ( false === $choices ) {
$choices = array();
$ids = get_posts( array( 'post_type' => $wpide_acf_choice_type, 'post_status' => 'publish', 'posts_per_page' => 200, 'orderby' => 'title', 'order' => 'ASC', 'fields' => 'ids', 'no_found_rows' => true ) );
foreach ( $ids as $id ) {
$choices[ $id ] = get_the_title( $id );
}
set_transient( $key, $choices, DAY_IN_SECONDS );
}
$field['choices'] = $choices;
return $field;
} );
add_action( "save_post_{$wpide_acf_choice_type}", function () use ( $wpide_acf_choice_type ) {
delete_transient( 'wpide_acf_choices_' . $wpide_acf_choice_type );
} );
add_action( 'deleted_post', function ( $post_id, $post ) use ( $wpide_acf_choice_type ) {
if ( $post && $wpide_acf_choice_type === $post->post_type ) {
delete_transient( 'wpide_acf_choices_' . $wpide_acf_choice_type );
}
}, 10, 2 );
Notes
Set the field name and the source post type. The list is cached until a post of that type is saved or deleted.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.