ObjectCache::get()publicWC 1.0

Retrieve a cached object, and if no object is cached with the given id, try to get one via get_from_datastore method or by supplying a callback and then cache it.

If you want to provide a callable but still use the default expiration value, pass "ObjectCache::DEFAULT_EXPIRATION" as the second parameter.

Method of the class: ObjectCache{}

No Hooks.


Object|Array|null. Cached object, or null if it's not cached and can't be retrieved from datastore or via callback.


$ObjectCache = new ObjectCache();
$ObjectCache->get( $id, $expiration, $get_from_datastore_callback );
$id(int|string) (required)
The id of the object to retrieve.
Expiration of the cached data in seconds from the current time, used if an object is retrieved from datastore and cached.
Optional callback to get the object if it's not cached, it must return an object/array or null.
Default: null

ObjectCache::get() code WC 8.9.0

public function get( $id, int $expiration = self::DEFAULT_EXPIRATION, callable $get_from_datastore_callback = null ) {
	if ( ! is_string( $id ) && ! is_int( $id ) ) {
		throw new CacheException( "Object id must be an int or a string for 'get'", $this );

	$this->verify_expiration_value( $expiration );

	$data = $this->get_cache_engine()->get_cached_object( $id, $this->get_object_type() );
	if ( null === $data ) {
		$object = null;
		if ( $get_from_datastore_callback ) {
			$object = $get_from_datastore_callback( $id );

		if ( null === $object ) {
			return null;
		$this->set( $object, $id, $expiration );
		$data = $this->last_cached_data;

	return $data;