Opened 7 years ago
Last modified 3 years ago
#43360 new enhancement
Third parameter for get_option function to return default value instead of empty string
Reported by: | farhan.noor | Owned by: | |
---|---|---|---|
Milestone: | Awaiting Review | Priority: | normal |
Severity: | normal | Version: | 4.9.4 |
Component: | Options, Meta APIs | Keywords: | close 2nd-opinion has-patch |
Focuses: | Cc: |
Description
get_option($option, $default = false)
function returns empty string if the required field exist but doesn't contain any value e.g. NULL or empty string.
For example, there is an option field 'test' exist in the option table but without any value(NULL or empty). Now get_option('test', 'Hello World')
function will return an empty string as it is; from the database but developer may be expecting "Hello World" in return.
To avoid this situation third parameter may be introduced for get_option()
function which will decide to return NULL/empty-string or default value. Here is my proposed solution
get_option( $option, $default = false, $return_null = true)
Now calling get_option('test', 'Hello World', false)
function for above problem will return default value which is Hello World.
wp-includes\options.php file requires little changes to address the above enhancement.
Attachments (2)
Change History (5)
#2
in reply to:
↑ description
@
7 years ago
- Component changed from General to Options, Meta APIs
- Keywords close 2nd-opinion added; has-patch removed
Hi @farhan.noor, welcome to WordPress Trac! Thanks for the report.
For example, there is an option field 'test' exist in the option table but without any value(NULL or empty). Now
get_option('test', 'Hello World')
function will return an empty string as it is; from the database but developer may be expecting "Hello World" in return.
That seems like expected behavior to me. All scalar option values ultimately stored in a longtext
field in the database, which means that they're retrieved as strings, and an empty string is a valid value. See the discussion in #31820.
You could use the option_{$option}
filter to perform a more strict check, see an example in comment:3:ticket:31820.
option.php is not a proper patch, see the handbook entry on submitting a patch.
#3
@
7 years ago
- Keywords has-patch added
Hi SergeyBiryukov
Thank you for your quick response. I have created a patch as per instructions & is attached herewith.
My proposed solution will not affect default behavior of the function but it will add another enhancement to the function when using with 3rd parameter. In many situations NULL values are considered as unanswered hence default value in-place of NULL/empty is required. This patch will work fine in that situation, without 3rd parameter it will keep working as before.
Patch