Dynamically populate a select field's choices

Hi,

I'm want to populate a select option field with information from my database (with info from a field in a custom post type). I'm using the great Advanced Custom Fields plugin.

However, I'm not quite sure how to do it.

I found this article http://www.advancedcustomfields.com/resources/dynamically-populate-a-select-fields-choices/ however I do not think it quite gives me the answer I'm looking for.

Now, I tried to use this option:

function my_acf_load_field( $field )
{
    $field['choices'] = array(
        'custom' => 'My Custom Choice'
    );

    return $field;
}

// acf/load_field/name={$field_name} - filter for a specific field based on it's name
add_filter('acf/load_field/name=navn_pa_auktionshus', 'my_acf_load_field');

And actually it seems to be working, but, it only adds the info from the 'custom' => 'My Custom Choice' which I have to add. However, I want it to be populated with info from the database from a certain field.

I hope you can help me out here :slight_smile:

Sincerely,
Mika

  • Tyler Postle

    Hey Mika,

    Hope you're doing well today and thanks for your question!

    Just to get some clarification, are you wanting to pre-populate the default selection or wanting to dynamically produce the selections? Are the possible selections not always the same?

    This thread here may provide some further guideance if it is the latter: http://wordpress.org/support/topic/plugin-contact-form-7-populate-select-box-from-database

    Has to do with a different plugin but the principle should still apply.

    If that doesn't help at all then post back and I'll flag one of our PHP experts to take a look :slight_smile:

    Look forward to hearing back!

    All the best,
    Tyler

    • Mika

      Hey Tyler.
      Thanks for your reply! :slight_smile:

      I have created a custom post type where my client can add different names of Auction Houses in Denmark. This means that the whole list of Auction House names is stored in the database.

      Now, I have also created another custom post type where my client can add auction events. One of the meta-fields (I'm using the ACF PRO plugin) in the post type is a dropdown selection where he can choose the name of the auction house.

      What I want to do is to show the list of the names of the Auction Houses from the database in the dropdown option selection field. Does that make any sense?

      So,

      1. Name is added in post type "Auction houses"
      2. Names are stored in the database
      3. New Auction Event is created
      4. The names are retrieved from the database into the Select dropdown option.

      I checked out the link you sent, but unfortunately it seems to be related to Contact Form 7, so there wasn't much too learn there unfortunately.

      Sincerely,
      Mika

  • Tyler Postle

    Hey Mika,

    Thanks for explaining that further :slight_smile:

    Sorry that article wasn't of any help. I am going to call in SLS(the coding experts) on this one to take a closer look. Then we can get their valuable input on this.

    Keep in mind, they have more responsibilities on the development end of things so may take longer to reply then a normal ticket.

    In the meantime, let us know if you have any other questions!

    All the best,
    Tyler

  • Jose

    Hey there @Mika,

    I'm afraid I would need some more clarification :slight_smile:

    I have created a custom post type where my client can add different names of Auction Houses in Denmark

    I understand that each Auction House is a post, right?
    If so, what is the custom post type name?
    What value do you want to show in the select options? the post title?

    Please advise.

    Also, it would be great if you can grant support access so that I can take a look and get a better idea of what you are trying to achieve.

    Cheers!
    Jose

    • Mika

      Hey Jose.

      Thanks for your reply. :slight_smile:

      The Action Houses (Auktionshuse in Danish) is a custom post type. When you add a Action House to the post type, you can add the name of the action house and a URL.

      The name of the pos type is "auktionshuse".

      Now, there is another post type named Auktioner (Auktioner in Danish). Here my client has the option to show upcoming Auctions. One of the fields that needs to be selected is the -->name of the auction house (Navn på auktionshus in Danish)<-- but instead of writing the name of the Auction house again for every event, he wants to be able to select the name from a dropdown list. The information/names of auction houses in this dropdown list, is the names that has been added under the Auction House post type.

      So basically:

      1. You add a auction house name under post type "auktionshuse"
      2. You then need to have the option to select the action house name under post type "auktioner" under field "Navn på auktionshus" using a select dropdown field.

      Does that make sense? :slight_smile:

      I have now granted you access to the website.

      Sincerely,
      Mika

  • Mika

    The way I presume it could work, is if we can query the Auction Houses Name's (navn_pa_auktionshus) meta value from the post-type "auktionshuse" for each of the auctions houses in the database.

    Then we can add an array of strings with the names of the auction houses in the code below where it current has one custom where it says "My Custom Choise".

    function my_acf_load_field( $field )
    {
        $field['choices'] = array(
            'custom' => 'My Custom Choice'
        );
    
        return $field;
    }
    
    // acf/load_field/name={$field_name} - filter for a specific field based on it's name
    add_filter('acf/load_field/name=navn_pa_auktionshus', 'my_acf_load_field');

    In fact, I'm sure this would work, but I'm not quite sure how to execute the database query to get the "navn_pa_auktionshus" and replace the 'My Custom Choice' with an array of strings.

    Sincerely,
    Mika

  • Jose

    Hey @Mika,

    Thanks for your patience here :slight_smile:

    I was taking a look at your site yesterday, and yes, your approach is correct. Also, there might be a couple of helper functions built into ACF that we could use.
    Since you are using the ACF Pro version, and I have no access to it, can you please provide me FTP credentials to try the code in your install?

    If you have some kind of dev environment running, that would be even better.

    Please send me the following information via contact form :

    - In the subject field add "Attn: Jose”
    - Link back to this thread
    - Include WP admin/network access (or keep support access enabled)
    - Include FTP
    - Include any relevant URLS for your site

    On the contact form, select "I have a different question", this ensures it comes through and gets assigned to me.

    Thanks,
    Jose

  • Jose

    Hey @Mika,

    It is working on your site now :slight_smile:

    Please notice that I needed to change the custom field name for Auktioner post type, since both Auktioner and Auktionshuse were using the same field name for the auktionhus value, causing an infinite loop into the filter. :disappointed:

    So, now the auktionshus field name for Auktioner post type is "navn_pa_auktion_auktionshus". Make sure to change it if you are using it in any other place in the code.

    The filter in your functions.php looks like this now:

    function my_acf_load_field( $field )
    {
      $field['choices'] = array();
    
      $auktionshuse_post_ids = get_posts(array(
          'post_type'     => 'auktionshuse',
          'numberposts'   => -1, // get all posts.
          'fields'        => 'ids', // Only get post IDs
        ));
      foreach($auktionshuse_post_ids as $auktionshuse_id){
          $auktionshuse_field = get_field('navn_pa_auktionshus', $auktionshuse_id);
           $field['choices'][$auktionshuse_field] = $auktionshuse_field;
      } 
    
      return $field;
    }
    
    // acf/load_field/name={$field_name} - filter for a specific field based on it's name
    add_filter('acf/load_field/name=navn_pa_auktion_auktionshus', 'my_acf_load_field', 999);

    Please let me know if everything works as you expect. I'll be glad to answer further questions. :slight_smile:

    Cheers,
    Jose

  • Mika

    Hey Jose.

    AMAZING! Thank you so much. This was exactly what I was looking for. I have definitely learned something with your approach to the issue!!

    There are actually two things which I would like to hear you about additionally, if you be so kind:

    1. Currently, the link that is associated with the Auction House name on the homepage: http://www.auktionsvinder.dk is added like this

    <a href="/auktionshuse"><?php the_field('navn_pa_auktionshus');?>.

    That is just a static link. However, is it possible also to pull in the actual link that was added on the "Add Auction House" page with the other information about the auction house, and then make the auction name, which was pulled in through the function you setup, a direct link to the URL that has been added for that auction house name.

    Ouch, I hope that make any sense. :smiley:

    Or in other words, when the user click on the auction house link on the homepage, then they will go straight to the associated URL (an external website) for that auction house?

    2. I talked with Vaughan about this, however, I haven't gotten an answer back from him. It is regarding https://premium.wpmudev.org/forums/topic/i-have-created-a-very-simple-website-for-a-client-where-he#post-739653.

    The query has been setup, however, there is somehow a bug because post older than the date set is not removed from the actual list on the homepage.

    Are you able to tell me why? And, possibly how I can fix it :slight_smile:

    Jose, thanks a lot man! I really appreciate!

    Sincerely,
    Mika

  • Jose

    Hey @Mika,

    First, I believe that this code above:
    <a href="/auktionshuse"><?php the_field('navn_pa_auktionshus');?>.

    should be changed now to use the new ACF field name 'navn_pa_auktion_auktionshus':
    <a href="/auktionshuse"><?php the_field('navn_pa_auktion_auktionshus');?>.

    I guess it still works for previous created Auktions, but it should not be working for the new ones. Please confirm.

    Now, regarding the actual question, the best approach would be to modify the code for the selector filter in order to use the Auktionshus ID instead of the Auktionshus name:

    Change this:

    foreach($auktionshuse_post_ids as $auktionshuse_id){
          $auktionshuse_field = get_field('navn_pa_auktionshus', $auktionshuse_id);
           $field['choices'][$auktionshuse_field] = $auktionshuse_field;
      }

    Into this:

    foreach($auktionshuse_post_ids as $auktionshuse_id){
          $auktionshuse_field = get_field('navn_pa_auktionshus', $auktionshuse_id);
           $field['choices'][$auktionshuse_field] = $auktionshuse_id;
      }

    Then, you can get the aktionhus ID like this:
    the_field('navn_pa_auktion_auktionshus');//This will return the ID now.

    In your template then you can get the name of the auktionshus and any other field (like the url) by doing something like this:

    $auktionshus_ID = the_field('navn_pa_auktion_auktionshus');
    $auktionshus_name = get_field('navn_pa_auktionshus', $auktionshus_ID);
    $auktionshus_URL = get_field('url', $auktionshus_ID);
    <a href="<?php echo $auktionshus_URL; ?>"><?php echo $auktionshus_name; ?>.

    Tried to keep the code as clear as possible :slight_smile:
    Please let me know if you have any question.

    Cheers,
    Jose

  • Mika

    Hey Jose.

    Thanks for your reply!

    1. <a href="/auktionshuse"><?php the_field('navn_pa_auktion_auktionshus');?> seems to be working, however, whenever I add it, it does effect all older posts, but it works on new ones. The older names for the auction houses disappears while the new one is shown.

    Is there any way we can fix this?

    Addtionally, what I would like to accomplish is not to use this static link /auktionshuse but to use the URL associated with the related Auction House which also was added as a field when the Auction House was added on the auction house post type.

    I tried to implement the rest of your code, however, my first issue is that when I change $auktionshuse_field; to $auktionshuse_id;, it is now the ID that is showing on the auctions houses select dropdown and not the actual names.

    And the rest of the code, did not seem to be working properly since it does not give me the actual names of the auction houses on the homepage.

    Thanks a lot for your help and patience Jose!

    Sincerely,
    Mika :slight_smile:

  • Jose

    Hey @Mika,

    It is working now on your site :slight_smile:

    It was just a small mistake I made (or you can blame ACF maybe). It is usng the key as value and the value as key. :disappointed:

    So, this should be switched:
    $field['choices'][$auktionshuse_field] = $auktionshuse_id;
    Into this:
    $field['choices'][$auktionshuse_id] = $auktionshuse_field;

    I also added a condition to support the old posts where the field name was 'navn_pa_auktionshus'.

    This is the new code, just for reference:

    $auktionshus_name = "";
    			$auktionshus_URL = "";
    			$auktionshus_ID = get_field('navn_pa_auktion_auktionshus');
    			if($auktionshus_ID){
    				$auktionshus_name = get_field('navn_pa_auktionshus', $auktionshus_ID);
    				$auktionshus_URL = get_field('url', $auktionshus_ID);
    			} else {
    				$auktionshus_name = get_field('navn_pa_auktionshus');
    				$auktionshus_URL = "/auktionshuse";
    			}

    The older names for the auction houses disappears while the new one is shown.
    Is there any way we can fix this?

    The new code shows the names as before, but it doesn't use the dynamic url. If you want it to work the same for all the posts, you need to edit all the old posts, select the auktionshus name and save. (I already did this with the first auktion in the list).

    Please let me know how it goes. :slight_smile:

    Cheers,
    Jose

  • Mika

    Hey Jose.

    Amazing, thank you so much! It seems to be working now. I defintely need to step up my PHP level so I can reach your level :smiley:

    Well, the only thing left, which I would love to have help with, is to find out why post that has exceeded the date of the auction still is showing.

    This is my query

    <?php
    
    $args = array(
    
    	'post_type' => 'auktioner',
    
    	'meta_key' => 'dato',
    
    	'orderby' => 'meta_value_num',
    
    	'posts_per_page' => 999,
    
    	'order' => 'ASC',
    
        'meta_query' => array(
    
           	'key' => 'dato',
    
         	'compare' => '>=',
    
         	'value' => current_time('timestamp'),
    
            'type' => 'numeric'
    
         	),
    
            'meta_value' => current_time('timestamp'),
    
    		'meta_value_num' => current_time('timestamp'),
    
    		'meta_compare' => '>='
    
    	);
    
    $the_query = new WP_Query( $args );
    
    ?>

    It should be working properly, however, it is not.

    Can you see what I have done wrong? :slight_smile:

    Once again, Jose, you are my new hero!! Thanks a lot!
    Sincerely,
    Mika

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.