Opened 5 years ago
Last modified 21 months ago
#37178 new enhancement
Add $cache_only parameter to get_option
Reported by: |
|
Owned by: | |
---|---|---|---|
Milestone: | Priority: | normal | |
Severity: | normal | Version: | |
Component: | Options, Meta APIs | Keywords: | has-patch dev-feedback needs-unit-tests |
Focuses: | performance | Cc: |
Description
When you do get_option()
and the option doesn't exist in the option cache, WordPress does a query to check whether that option exists and loads it. This is great as default behavior, but when you know that an option would have been autoloaded, you might not want that to happen.
I propose adding a parameter $cache_only
, which defaults to false, which, when set to true, returns false when there is no option set in the cache. The "workaround" currently would be to set an empty option, but that means adding unnecessary data to the database.
Attachments (2)
Change History (5)
@
5 years ago
Rewrote a bit :) Don't know in which scenario it could be handy. That one select isn't so perf expensive. If somebody is using get_option he/she needs to know if it exists, that's default consideration for me from the function name.
#1
in reply to:
↑ description
@
5 years ago
Replying to joostdevalk:
The "workaround" currently would be to set an empty option, but that means adding unnecessary data to the database.
Another workaround would be adding a pre_option_*
filter for that option that returns an empty string or null
to short-circuit the function and avoid the SQL query:
function wp37178_get_autoloaded_option( $option, $default = false ) { // prevent non-existent options from triggering multiple queries $notoptions = wp_cache_get( 'notoptions', 'options' ); if ( isset( $notoptions[ $option ] ) ) { return $default; } $alloptions = wp_load_alloptions(); if ( isset( $alloptions[$option] ) ) { $value = $alloptions[$option]; } else { $value = wp_cache_get( $option, 'options' ); } if ( ! $value ) { $value = null; } return maybe_unserialize( $value ); } add_filter( 'pre_option_myoption', 'wp37178_get_autoloaded_option' );
Patch, first go.