Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.