Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Talk:Function Reference/update option

I'm not exactly sure why this page was singled out for copyediting, but the example code section looks extremely confusing and overthought. The simple line  update_option( 'myhack_extraction_length', 255 );  would achieve the exact same result. Goldenapples 03:31, 22 May 2012 (UTC)

Example is unclear?

The example does not seem to be valid. It seems it is trying to get around the fact that you can't set autoload to 'no' when calling update_option() on an option that hasn't already been added:

<?php
$option_name = 'myhack_extraction_length' ;
$newvalue = '255' ;

if ( get_option( $option_name ) != $newvalue ) {
    update_option( $option_name, $newvalue );
} else {
    $deprecated = ' ';
    $autoload = 'no';
    add_option( $option_name, $newvalue, $deprecated, $autoload );
}
?>

A better example would seem to be:

<?php
$option_name = 'myhack_extraction_length' ;
$new_value = '255' ;
$existing_value = get_option($option_name);
if ($existing_value === false) {
    $autoload = 'no';
    $deprecated = null;
    add_option($option_name, $new_value, $deprecated, $autoload);
}
else {
    update_option($option_name, $new_value);
}
?>

Incorrect Description

The description says that you must sanitize the value but the parameter reference section says that you can store arrays, objects or whatever. These statements can't both be true.


I've removed that note from the page since it was unclear what exactly it was trying to say. update_option() SQL-escapes both the $option and $value, but it doesn't sanitize either of them, beside calling sanitize_option() on the $value. The option value does of course have to be escaped before it is displayed to a user to prevent XSS, for example, but what form of escaping is needed depends on the context in which the option value is being used. If an option value needs to be sanitized/validated beyond that, of course it is up to the developer to ensure that happens, by hooking into sanitize_option() or otherwise.
-Jdgrimes (talk) 20:42, 24 March 2016 (UTC)