Carbon-fields: select add_options() callback slows site down

Created on 8 Oct 2017  路  6Comments  路  Source: htmlburger/carbon-fields

I noticed while optimizing loading time of a site that when a select field is set with a callback in add_options() to get array of options, the callback is called on every WordPress load and slow the site when the callback calls DB for data.

I probably could save the values in a transient, but it would be better if the callbacks will be called only on edit post pages

Example:

Field::make('select', 'city')->add_options(get_cities() )

It it possible that the get_cities() function would be called only on edit post page instead of every site load?

Attached screenshot from monitor query which shows in wp-admin main page a query from a callback inside add_options( )

The field is:

Field::make('select', 'client_id', 'Client')->add_options(Client_Data::get_clients_select() )

select callback

This ticket may be about the same issue https://github.com/htmlburger/carbon-fields/issues/349

Thanks for this great plugin.

[type] question

All 6 comments

Hi @batz-bar ,

To improve performance pass the callback function's name as a string (or any callable) like this:

Field::make('select', 'city')->add_options( 'get_cities' )
// or
Field::make('select', 'client_id', 'Client')->add_options( array( Client_Data::class, 'get_clients_select' ) )

This way the callable will be called only when the select needs to load/display the options.

I added a note to our internal TODO to improve the docs with emphasis on this way of using add_/set_options.

This ticket may be about the same issue #349

Yes, exactly my problem! Obviously I couldn't reproduce it because I used a callback function's name in my example.

Is it possible to pass variables to a callback function?

Just wrap it in an anonymous function:

Field::make('select', 'city')
    ->add_options( function() {
        return get_cities( 'my', 'custom', 'args' );
    } );

EDIT:

Updated example to remove the use () statement - don't know why I complicated the example.

Thank you. I'll try it out

Got it working. I ended up using an easier case of an anonymous function.

Field::make('select', 'city')
    ->add_options( function() {
        return get_cities( 'Amsterdam' );
    } );
Was this page helpful?
0 / 5 - 0 ratings