I need to see if an option, and if does, get the value. If not, I need to add it.
The Codex provides:
<?php
$option_name = 'myhack_extraction_length' ;
$new_value = '255' ;
if ( get_option( $option_name ) != $new_value ) {
update_option( $option_name, $new_value );
} else {
$deprecated = ' ';
$autoload = 'no';
add_option( $option_name, $new_value, $deprecated, $autoload );
}
Which supposedly updates the option name myhack_extraction_length with the value 255. If the option does not exist then use add_option and set autoload to no.
However, it seems to me that the second half could be called in two ways, if the option does not exist OR if the new value==the option
Is this correct?
The logic on the IF THEN ELSE does seem a bit wonky. If I’m reading it correctly…
The call to get_option( $option_name ) will return FALSE if the option does not exist or if it has no value.
So the IF would be executed:
The update_option() call would then update the value or create the option with $new_value.
The ELSE would be called if:
I don’t recommend to use
if (!(get_option("XXXX"))
approachto check for existence
, as it fails withfalse/null/0/empty
legitimate value.I suggest:
code:
(I had also submitted this feature as CORE request)
I believe that the best approach to this issue is to create IF-ELSE logic like this one:
Logic: get_option() will return TRUE if that option does exist. In this case we can simply update that option with some value we want to add. This is done by
update_option('some_option','value_we_want_to_add')
. On the other hand, if some_option doesn’t exist, get_option will return FALSE and activate ELSE block. Inside else block we gave instruction to create this “some_option” and assign value we want to it.Optionally, this logic can be changed to match more advanced requirements.
If you mean “when does the ‘if’ execute and when does the ‘else’ execute, then “No”. Look at the condition:
if ( get_option( $option_name ) != $new_value ) {
If the option does not exist–
false != '255'
istrue
— then the first part executes. It also executes if the option exists and the values don’t match —'123' != '255'
istrue
.The
else
executes only if the values do match–'255' != '255'
is false, so theelse
part runs. They could match on anything, numbers, strings, booleans– aka true or falseI struggled a bit with these kind of options management and did it with a different approach…
@Steve is answering you perfectly, I’m just adding a possibility on how to approach options managing.
Try This
Function checking if $arg / string / exist in mySQL.
$arg must be a string / the name of your option /
If the function returns true -> option exist; returns false -> there is no option with this name.
/**
* Check If Option Exist;
* @param String
* @return boolean;
*/
Example:
Result:
true / false
Example: ( create option if not exist ):
And your answer may be is: