Home › Forums › General Issues › How to Narrow Categories Displayed in ACF? › Reply To: How to Narrow Categories Displayed in ACF?
No problem! In that case, try this.
function acf_load_field_choices( $field ) {
// Create an empty array
$field['choices'] = array();
// Get parent categories and order by name
$categories = get_categories(
array(
'orderby' => 'name',
'hide_empty' => 0,
)
);
// Create a counter variable for the array
$i = 0;
foreach( $categories as $category ) {
// Get the top level categories
if ( $category->parent == 0 ) {
$field['choices'][$i] = $category->name;
$i++;
// Get subcategories within the parent category only
foreach ( $categories as $subcategory ) {
if ($subcategory->parent == $category->term_id) {
$field['choices'][$i] = $subcategory->name;
$i++;
}
}
$i++;
}
}
// Return the result
return $field;
}
add_filter('acf/load_field/name=test', 'acf_load_field_choices');
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
Plugin boilerplates can do some of the heavy lifting during initial development. We look at four options to speed up your plugin creation. https://t.co/ZtMsdBxAHw
— Advanced Custom Fields (@wp_acf) June 5, 2023
© 2023 Advanced Custom Fields.
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.