0

I am currently writing a plugin that allows all authors to be listed on a page. I've created an options page and wanted to create a function that allows administrators to exclude certain authors from the page.

The options page is a list of checkboxes with the Author ID as a value. When the form is submitted, checkboxes are passed as an array to the processing function (which is below), the function combines all the values, and inserts the value into the database using "update_option()".

function wp_applugin_options_process() { 

  $arr = $_POST["excludeid"];
  $excludeid = implode(" ",$arr);
  $excludeid = esc_html( $excludeid);

  update_option("wp_applugin_excludeids", $excludeid );

}

By default, the "update_option" creates the option, but leaves it empty. However, if I break the plugin, by placing the line "echo get_option("wp_applugin_excludeids")" right after the "update_option" line, not only does it echo the correct values, but the values are also loaded into the database. If I go to a page that doesn't run wp_applugin_options_process, the option "wp_applugin_excludeids" is deleted.

Any ideas?

1 Answer 1

1

Where are you calling wp_applugin_options_process()?

If you call it, and $_POST["excludeid"] isn't set, then you're effectively calling:

update_option("wp_applugin_excludeids", null );

So if you're calling this function on every page load, or even just when your admin page is loaded, then you're automatically deleting your option. You should put a check in your function to make sure that the variable is set before doing anything with it:

function wp_applugin_options_process() { 
    if(!isset($_POST["excludeid"])) return;

    $arr = $_POST["excludeid"];
    $excludeid = implode(" ",$arr);
    $excludeid = esc_html( $excludeid);

    update_option("wp_applugin_excludeids", $excludeid );

}
2
  • 1
    True. Even if POST processing should be done in "load-{hook-name}" actions to make sure we do it on the right page. Because there are situations with multiple checkboxes when nothing will be set in $_POST if none is selected. Nov 1, 2011 at 22:25
  • 1
    Cheers guys, both of you solved it :)
    – Rhys Wynne
    Nov 1, 2011 at 23:29

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.