WordPress.org

Make WordPress Core

Opened 2 years ago

Last modified 23 months ago

#37178 new enhancement

Add $cache_only parameter to get_option

Reported by: joostdevalk Owned by:
Milestone: Awaiting Review 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)

37178.diff (1.3 KB) - added by joostdevalk 2 years ago.
Patch, first go.
37178.2.diff (1.1 KB) - added by michalzuber 2 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.

Download all attachments as: .zip

Change History (5)

@joostdevalk
2 years ago

Patch, first go.

@michalzuber
2 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 @SergeyBiryukov
2 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' );

#2 @SergeyBiryukov
2 years ago

  • Component changed from General to Options, Meta APIs

#3 @jipmoors
23 months ago

  • Keywords needs-unit-tests added
Note: See TracTickets for help on using tickets.