The subtle differences between get_alloptions, wp_load_alloptions and get_option

WordPress code had been very bad and made me waste several hours because of lack of proper documentation :(. All I was trying to do was to write a script that will do a simple search and replace on the text part of a text widget and each time I  would run the script the widget will stop being displayed.

My code was very simple

$opts = get_alloptions();
foreach ($opts  as $k=>$ogt) {
  if it is a text widget {
    $opt = searchandreplace($opt);
    update_option($ov,$opt);
  }
}

Turns out get_alloptions is deprecated  in favour of wp_load_options (i.e. the codex entry for it is wrong) therefor it does cache the options,but the array it returns is raw values which might be seialized while get_option return unserialized data. That was the source for my problem as I was assuming that get_alloptions is just a sytax sugar for calling get_option for each option at once.

The working code looks like

$opts = wp_load_options();
foreach ($opts  as $ov=>$opt) {
  if it is a text widget {
    $opt=get_option($ov); // already cached so no extra DB access
    $opt = searchandreplace($opt);
    update_option($ov,$opt);
  }
}

And then it gets even worse as suddenly I discover that wp_load_options returns only the autoloaded options but I want my code to be generic enough to work on not autoloaded as well so there is basically no alternative but to do a direct DB access

$opts = $wpdb->get_results( "SELECT option_name FROM $wpdb->options");
foreach ( (array) $opts  as $ov) {
  if it is a text widget {
    $opt=get_option($ov); // already cached so no extra DB access
    $opt = searchandreplace($opt);
    update_option($ov,$opt);
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *