3

I've looked at the Settings API codex page, https://codex.wordpress.org/Settings_API, and I can't find anything related to setting autoload to no for any options using the Settings API.

Is there any way to achieve this using the Setttings API? Asking because I have many DB table options entries that were created using register_setting and all of the options have autoload set to yes.

I need to optimize this because hundreds of entries are being loaded on every page load unecessarily.

1
  • So is it autload by default? That would be actually great! Where did you find it's autoloading ? :)
    – jave.web
    May 5, 2021 at 23:41

2 Answers 2

2

The only way to accomplish this is to add the option to the database yourself before the Settings API does so. To do this, add a 'sanitize_callback' to the register_settings function:

register_setting ('my_options', 'my_option_name', array ('type' => 'string', 'sanitize_callback' => 'my_function_name'));

Then, in your function, update the option yourself:

function my_function_name ($value) {
    update_option ('my_option_name', $value, false);
    return $value;
}

`

3
  • This breaks the form for me – when I submit the form, the page changes to /wp-admin/options.php and I get the error PHP Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 262144 bytes). Perhaps this causes an infinite loop, where WP keeps trying to update the option. Sep 19, 2021 at 10:20
  • It could only get stuck in a loop if you have other actions or filters that trigger when you update options. Sep 20, 2021 at 19:42
  • Thanks @mark-barnes, I see – that's quite possible. Sep 21, 2021 at 15:05
0

After trying many possible solutions (most of them go into an infinite loop) this one is working for me.

I use the add_option_{$option} hook and then I do the following:

public function change_autoload_to_no( $option, $value )
{

    update_option( $option, '', 'no' );
    update_option( $option, $value, 'no' );

}

This might not be the most "elegant" solution but it works. I guess other option is to modify the value directly with sql.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.