Support

Account

Home Forums ACF PRO Check if field key exist

Solved

Check if field key exist

  • With the help of ACF Pro, I’m building a plugin that involves checking a field key for choices of a specific field. With my local environment I have the following setup…

    $field_key = “field_5b5b34f4ed085”;
    $field = get_field_object($field_key);

    foreach($field[‘choices’] as $mkey => $mvalue) {
    //DO STUFF
    }

    …That works for me in my local environment. But sense I’m porting my plugin into 3 different environments, I would like to check if the given key exists or is false. And if so, try another. Is setting up that conditional possible with ACF Pro? Here are all my keys to check against…

    * field_5b5b34f4ed085
    * field_5b5b34f4ed085
    * field_5b648d8589d37

    ..and for the first one that exists, use it. Is this possible? If so, where do I start?

    Many thanks!

  • Is there a possibility that none of them will exist?
    I would do something like this

    
    $possible = array('field_5b5b34f4ed085', 'field_5b5b34f4ed085', 'field_5b5b34f4ed085');
    $field_key = false;
    $field = false;
    foreach ($possible as $key) {
      $field = get_field_object($key);
      if ($field) {
        $field_key = $key;
        break; // causes exit of loop when field is found
      }
    }
    // if field is not found
    // $field_key and $field will both == false
    
    // if field is found
    // $field_key == the existing field key here
    // $field == existing field object
    
    
  • Thank you so much John for the feedback! I just discovered a simple way to solve this process.

    I created a variable in my wp-config.php file to determine what environment I’m in. If that value matched “local”, or “dev” or “prod”, that that determines which key field gets loaded.

    Its solving my problem so I believe this is resolved. Many thanks!

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

The topic ‘Check if field key exist’ is closed to new replies.