0

I am using following function to get the options stored in wordpress.

function get_settings( $option ) {
    $options = get_option( 'my_options', my_default_options() );
    return $options[ $option ];
}

In the above function my_default_options() returns an array which has default values. Now if I call the above function like: get_settings("title"); it will work fine if the "title" exists in the default options array.

However if title does not exist in the default options array, then I get the following warning:

Notice: Undefined index:

How can I fix this notice? I tried following:

function get_settings( $option ) {
    $defaults = my_default_options();

    if(in_array($option, $defaults)){
        $options = get_option( 'my_options', my_default_options() );
        return $options[ $option ];
    }
}

But it still returns same notice.

2 Answers 2

1

Make sure if it exists or not using isset

function get_settings( $option ) {
    $defaults = my_default_options();

    if(in_array($option, $defaults)){
        $options = get_option( 'my_options', my_default_options() );
        return isset($options[ $option ]) ?  $options[ $option ] : '';
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Use the function array_key_exists. in_array search for value while array_key_exists search for keys/indexes :

function get_settings( $option ) {
    $options = get_option( 'my_options', my_default_options() );
    if(array_key_exists($option, $options))
        return $options[ $option ];
    return "unknown";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.