Useful Snippets

Welcome!


This blog is used to collect useful snippets related to Linux, PHP, MySQL and more. Feel free to post comments with improvements or questions!

Are your smart devices spying on you? Make better purchasing choices and find products that respect your privacy at Unwanted.cloud

RSS Latest posts from my personal blog


Subscribe to RSS feed


Reordering field groups in Advanced Custom Fields

Stanislav KhromovStanislav Khromov

When you add field_groups to acf_form() you expect that the field groups will be added in the order you add them to your field_groups array. For example:

acf_form(array('field_groups' => array(604, 142));

This should display group 604 and 142, in that order. Unfortunately it doesn’t. So we need to figure out how to reorder fields. Digging around the code I found the get_field_groups hook which we can use for this.

Example code:

add_filter('acf/get_field_groups' , 'theme_reorder_field_groups');
function theme_reorder_field_groups($field_groups)
{
    $temporary_field_groups = array();

    //Put all groups in new indexed array
    foreach($field_groups as $field_group)
        $temporary_field_groups[$field_group['id']] = $field_group;

    //Identify if it's our specific ACF form by its field groups
    //In our case we have a form with the field group ids 142 and 604,
    //So we only want this code to run for that specific form
    if(array_key_exists(142, $temporary_field_groups) && array_key_exists(604, $temporary_field_groups))
    {
        $new_field_group = array();

        //Reorder the fields. The fields will appear in the order they are added to the $new_field_group array
        $new_field_group[] = $temporary_field_groups[604];
        $new_field_group[] = $temporary_field_groups[142];

        return $new_field_group;
    }

    return $field_groups;
}

Note: Since there is no way to uniquely identify the form, we are settling with only using the reordering code if we can find both of our field groups.

Full-stack impostor syndrome sufferer & Software Engineer at Schibsted Media Group

Comments 0
There are currently no comments.