Created
July 7, 2016 11:52
-
-
Save kirandash/cfa0b68dc2ce90cf9b3f2aff3a3d0eca to your computer and use it in GitHub Desktop.
Use the code snippet to dynamically populate a select field's choices in ACF.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//dynamically populate a select fields choices | |
function acf_load_category_field_choices( $field ) { | |
// reset choices | |
$field['choices'] = array(); | |
// get the textarea value from options page without any formatting | |
$choices = get_categories(); | |
$i = 0; | |
$len = count($choices); | |
$choicestring = ''; | |
foreach( $choices as $choice ) { | |
if ($i == $len - 1) { | |
$choicestring .= $choice->slug; | |
}else{ | |
$choicestring .= $choice->slug.'*#@'; | |
} | |
$i++; | |
} | |
// explode the value so that each line is a new array piece | |
$choicestring = explode("*#@", $choicestring); | |
// remove any unwanted white space | |
$choices = array_map('trim', $choicestring); | |
// loop through array and add to field 'choices' | |
if( is_array($choices) ) { | |
foreach( $choices as $choice ) { | |
$field['choices'][ $choice ] = $choice; | |
} | |
} | |
// return the field | |
return $field; | |
} | |
add_filter('acf/load_field/name=slider_category', 'acf_load_category_field_choices'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment