Home › Forums › Backend Issues (wp-admin) › sort by adding a field with php (acf_add_local_field9
I have added a field to a group, I need to change the order in which the field appears in the WordPress admin.
I create the group in the parent theme but add the field in the child theme, this works correctly but I cannot change the order in which the field is displayed.
acf_add_local_field( array(
'key' => 'field_104624e64aad7',
'label' => __('Content', 'nmf'),
'name' => 'content',
'type' => 'wysiwyg',
'instructions' => '',
'required' => 0,
'conditional_logic' => 0,
'parent' => 'group_5d4c3300b55ad',
) );
I have searched a lot but unfortunately I can’t find a solution for this.
The reason is that there is no solution, at least not an easy one.
ACF adds fields to the group in the order that they are created. In order to insert a field between two other fields you would have to make changes and you would not be able to use acf_add_local_field()
Some thoughts on how you can do this.
One way is that you can add a filter between adding fields of your field group if you are doing this in PHP in the parent theme.
// parent theme code
// a field you are adding
acf_add_local_field(...);
// where you want to allow insertion of other fields
// the you would build and action filter that uses your hook
do_action('allow_insertion_here');
// another field you are adding
acf_add_local_field(...);
The problem with this is that you’d end up with dozens of hooks if you want to be able to insert fields between every other field.
Another way would be to use the acf/validate_field_group
filter hook. This is an undocumented hook in ACF. It passes the field group array before it is added. In order to use this your field group would need to be loaded from the DB, JSON or it the field group would need to be added using the PHP generated by ACF when you export a field group to PHP.
add_filter('acf/validate_field_group', 'add_fields_to_group');
function add_fields_to_group($gorup) {
// you need to loop over all the fields until you find
// the one before where you want to insert a new field
$fields = $group['fields'];
$new_fields = array();
foreach ($fields as $field) {
if ($field['name'] == 'field you want to insert after') {
$new_fields[] = $field;
$new_fields[] = array(/* array of field argument */);
} else {
$new_fields[] = $field;
}
}
// set group fields to new fields and return
$group['fields'] = $fields;
return $group;
}
You must be logged in to reply to this topic.
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!
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 Privacy Policy. If you continue to use this site, you consent to our use of cookies.