Dynamic icon select in Advanced Custom Fields

For more information, see Dynamic dropdown fields in ACF.

<?php
/**
 * Dynamic Icon Select 
 * Lists icons found in theme's /assets/icons directory 
 *
 */
function ea_acf_icon_select( $field ) {
	$field['choices'] = array( 0 => '(None)' );
	if( ! function_exists( 'ea_get_theme_icons' ) )
		return $field;
	$icons = ea_get_theme_icons();
	foreach( $icons as $icon ) {
		$field['choices'][ $icon ] = $icon;
	}
	return $field;
}
add_filter('acf/load_field/name=icon', 'ea_acf_icon_select' );
/**
 * Theme Icons
 *
 */
function ea_get_theme_icons() {
	$icons = get_option( 'ea_theme_icons' );
	$version = get_option( 'ea_theme_icons_version' );
	if( empty( $icons ) || ( defined( 'CHILD_THEME_VERSION' ) && version_compare( CHILD_THEME_VERSION, $version ) ) ) {
		$icons = scandir( get_stylesheet_directory() . '/assets/icons' );
		$icons = array_diff( $icons, array( '..', '.' ) );
		$icons = array_values( $icons );
		if( empty( $icons ) )
			return $icons;
		// remove the .svg
		foreach( $icons as $i => $icon ) {
			$icons[ $i ] = substr( $icon, 0, -4 );
		}
		update_option( 'ea_theme_icons', $icons );
		if( defined( 'CHILD_THEME_VERSION' ) )
			update_option( 'ea_theme_icons_version', CHILD_THEME_VERSION );
	}
	return $icons;
}

Bill Erickson

Bill Erickson is the co-founder and lead developer at CultivateWP, a WordPress agency focusing on high performance sites for web publishers.

About Me
Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk