Support

Account

Home Forums General Issues Country Flags (graphics/icons) with ACF? Reply To: Country Flags (graphics/icons) with ACF?

  • This is how I would do this…

    The basics

    Upload all of the flag images to a folder on the server, for this example I will assume I have put them in /wp-content/themes/your-theme/flags/. The file names of these flags would include information I want to display. For example the file name for the US flag might be “US-USA-United_States.png”. I will explain US is the 2 character ISO country code, USA is the 3 character ISO code and ‘United_States” is the country name. These 2 parts are separated with hyphens and spaces are replaced with underscores. You can use whatever you want here based on what text you want to appear for selection.

    I would create a select field for the flag. “Stylised UI = Yes” this will allow images to be shown and will also create search using select2.

    I would dynamically generate the choices for this field from the files that exist in the folder.

    
    add_filter('acf/prepare_field/name=your-flag-field-name', 'populate_flag_field', 20);
    function populate_flag_field($field) {
      $choices = array();
      $dir = get_template_directory().'/flags';
      $files = scandir($dir);
      if ($files) {
        foreach ($files as $file) {
          if (is_dir($dir.'/'.$file)) {
            // skip folders
            continue;
          }
          // only allow png images
          $file_info = pathinfo($file_name);
          if ($file_info['extension'] != 'png') {
            continue;
          }
          // build label
          $label = $fileinfo['filename'];
          // pretty it up
          $label = str_replace('-', ' - ', $label);
          $label = str_replace('_', ' ', $label);
          // add image
          $label .= ' <img src="'.get_template_directory_uri().'/flags/'.$file.'" />';
          // add choice
          $choices[$file] = $label;
        } // end foreach file
      } // end if files
      return $choices;
    } // end function
    

    The I would create an acf/format_value filter

    
    add_filter('acf/format_value/name=your-flag-field-name', 'format_flag_field', 20, 3);
    function format_flag_field($value, $post_id, $field) {
      if ($value) {
        $value = '<img src="'.get_template_directory_uri().'/flags/'.$value.'" />';
      }
      return $value;
    }