Support

Account

Home Forums Backend Issues (wp-admin) Dynamically populating Select Field with CPT Posts

Solved

Dynamically populating Select Field with CPT Posts

  • Hello everyone,

    I absolutely love ACF and find something new every day. I am familiar with the Dynamically populate a select field’s choices tutorial and have used it to great effect in my options pages. But I am attempting to get the names of posts in a custom post type and have them dynamically populate in a select field.

    While the below code works, it has the adverse effect of rewriting the permalink of a post found in a SEPARATE post type and preventing the data from displaying at all. As soon as I remove this code from my functions file, everything (including the permalink) restores itself.

    I’m certain its something small I’m missing. Looking forward to any help you all can give in this matter.

    function acf_load_vehicle_field_choices( $field ) {
    
        // reset choices
        $field['choices'] = array();
    
        //do the query of Vehicle Info for all the vehicles available
        $args = array(
          'numberposts'	=> -1,
          'post_type'		=> 'vehicle_info'
    
        );
        // Do your stuff, e.g.
        $the_query = new WP_Query( $args );
        if ($the_query->have_posts()) {
          global $post;
          while( $the_query->have_posts() ){
            $the_query->the_post();
            $value = get_post_field( 'post_name', get_the_ID() );
            $label = get_the_title();
            // append to choices
            $field['choices'][ $value ] = $label;
          }
          wp_reset_postdata();
        }
        // return the field
        return $field;
    
    }
    
    add_filter('acf/load_field/name=vehicle', 'acf_load_vehicle_field_choices');
  • Ended up resolving this on my own using get_terms().

    • csaborio

    • September 16, 2019 at 10:42 pm

    Hey, was looking at the forum and saw this…I think in the following code:

    if ($the_query->have_posts()) {
          global $post;
          while( $the_query->have_posts() ){

    You do not need:

    global $post;

    You are querying from here and going through the loop based on the results, you have the actual post data, no need to bring the global.

  • @csaborio dude thanks! That seemed to do the trick completely better than my own solution. Thought I needed to grab the global post variable in order to loop through them all.

    • csaborio

    • September 18, 2019 at 3:32 pm

    @kenancross absolute pleasure, I love learning new things in these forums as well as lending a helping hand when I can! 🙂

Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.