0

Recently a plugin I am developing begun throwing up an error whenever I deleted the plugin options (restored them to default).

I'm using the Settings API within the plugin in question, and on another page I am checking the settings assigned to those options -

$login_settings = get_option('fgw_login', array());

Upon activation and after I save the settings this was workin fine, with the default array() being assigned to $login_settings if required.

However I was getting an error whenever I tried to reset the plugin options to their defaults. Basically I wanted to delete the key/value pair from the wp_options database.

/**
 * Sanitize the option on save
 */
public function on_save_settings($input){

    /** Check to see if the options should be restored to default */
    if(isset($_POST['delete'])) :
        delete_option('fgw_login');
        return;
    endif;

    if(!isset($_POST['submit'])) return;    // Ensure the user is supposed to be here

    {more stuff here, but not relevant}

}

However it seemed that delete_option('fgw_login'); wasn't actually deleting the key/value pair for the option, but rather just the value, leaving the key in place.

This was a problem because I was checking the $login_settings for a specific array key value, but as $login_settings was being set as an empty string I was getting an error.

I could have simply added a check to see if $login_settings was an array, but I was curious so I did some digging. If you are at all interested, please see my answer below...

1

The problem here was caused because I was using a sanitize callback declared in register_settings() (the on_save_chages() function below).

This callback will ultimatly update the database with whatever value is returned, creating the fgw_login key if it does not exist.

To ensure that I always had my default empty array if required I made the following simple change, returning an empty array when the options were reset as opposed to nothing -

/**
 * Sanitize the option on save
 */
public function on_save_settings($input){

    /** Check to see if the options should be restored to default */
    if(isset($_POST['delete'])) :
        delete_option('fgw_login');
        return array();                 /** <-- THIS IS ALL I HAD TO DO */
    endif;

    if(!isset($_POST['submit'])) return;    // Ensure the user is supposed to be here

    {more stuff here, but not relevant}

}

While the problem exposed my code for not making the proper checks, I'm glad that I was afforded the oppurtunity to delve into the Settings API in greater depth and encourage any users of it's awesomeness to do the same :)

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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