Support

Account

Home Forums Bug Reports User Field Create Field Loop Optimization

Unread

User Field Create Field Loop Optimization

  • I recently ran into an issue where I encountering timeouts when editing posts. For the life of me I couldn’t figure out what the problem was until one error log entry got me started down the right track. It turned out that the User Field being created on the post was causing our memory to be exhausted when trying to edit. This wouldn’t have shown up except our host had us a low memory usage setting for PHP. In an effort to fix this I ran into code in the ACF plugin that looks like it could afford some rework to make it a bit more efficient. I’m placing my proposed code below. I originally ran into this issue with ACF 4 but it applies equally to ACF PRO.

    The biggest issue is that this field requires every user from the DB to pulled into sort out whether that user belongs in the dropdown. Given that every user is assigned a role and that is an option for filtering our users in the admin, I propose that the filters be used in the original query so as to not pull in all the users but only the only the ones that fit into the roles the field is looking to sort through.

    This is if /fields/user.php function: ajax_query in ACF PRO starting at line 137. I have made some code to at least speed up the process, but I think this entire function could be rewritten a bit better with this query based approach in mind:

    
    global $wpdb;
    $args['meta_query'] = array('relation' => 'OR');
    $user_role_filter = array();
    foreach ($editable_roles as $role => $role_info)
    {
    	$user_role_filter[] = array(
    		'key' => $wpdb->prefix . 'capabilities',
    		'value' => $role,
    		'compare' => 'like',
    	);
    }	
    $args['meta_query'] = array_merge($args['meta_query'], $user_role_filter);
    

    Essentially I am putting all the roles into the meta_query so that the get_users function will now just pull in the users that fit the roles instead of sorting that out in the loop below the get_users call.

    If it’d help I could rewrite the whole function to show what my thoughts were on it.

Viewing 1 post (of 1 total)

The topic ‘User Field Create Field Loop Optimization’ is closed to new replies.