Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question

3 Answers 3

up vote 0 down vote accepted

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:

  1. when the option doesn't exist and $new_value != FALSE
  2. the option has no value and $new_value != FALSE
  3. the option exists and has a value that is != $new value

The update_option() call would then update the value or create the option with $new_value.

The ELSE would be called if:

  1. the option exists and has the same value as $new_value
  2. the option does not exist and the $new_value == FALSE
share|improve this answer

Is this correct?

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' is true-- then the first part executes. It also executes if the option exists and the values don't match --'123' != '255' is true.

The else executes only if the values do match-- '255' != '255' is false, so the else part runs. They could match on anything, numbers, strings, booleans-- aka true or false

share|improve this answer

This is simpler- check if option doesnt exist (or empty). i.e.:

if(!get_option('speccc_nameee')){
    update_option('speccc_nameee', 'first_default_value');
}
share|improve this answer
    
Please add an explanation to your answer: why could that solve the problem? –  toscho Mar 13 at 19:57

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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