Skip to content

Instantly share code, notes, and snippets.

@khleomix
Last active February 16, 2022 22:10
Show Gist options
  • Save khleomix/f9e7e9532bfd9c9ca40e9f7fb231dcaf to your computer and use it in GitHub Desktop.
Save khleomix/f9e7e9532bfd9c9ca40e9f7fb231dcaf to your computer and use it in GitHub Desktop.
Load icon files dynamically as ACF select options
<?php
/**
* Load icons dynamically into the `icon_picker` select field.
*
* @param array $field field options.
* @return array new field choices.
*
* @author JC Palmes
*/
function acf_load_icon_picker_field_choices( $field ) {
// Reset choices.
$field['choices'] = array();
// Grab our icons array.
$icon_folder = get_template_directory() . '/build/images/icons';
$icons = list_files( $icon_folder, 2 );
// Loop through icons.
foreach ( $icons as $key => $icon ) {
if ( is_file( $icon ) ) {
$icon_name = str_replace( '.svg', '', basename( $icon ) );
}
$pretty_icon_name = str_replace( '-', ' ', $icon_name );
// Set values.
$field['choices'][ sanitize_title( $icon_name ) ] = ucfirst( $pretty_icon_name );
}
// Return the field.
return $field;
}
add_filter( 'acf/load_field/name=icon_picker', __NAMESPACE__ . '\acf_load_icon_picker_field_choices' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment