函数文档

wp_cache_get()

💡 云策文档标注

概述

wp_cache_get() 是 WordPress 中用于从缓存中检索内容的函数,通过键和组来定位数据。它返回缓存内容或失败时的 false,并支持通过引用参数判断是否找到缓存项。

关键要点

  • 函数签名:wp_cache_get( $key, $group = '', $force = false, &$found = null ),其中 $key 是必需的缓存键,$group 是可选分组(默认为空),$force 控制是否强制从持久缓存更新本地缓存(默认为 false),$found 是引用参数用于指示键是否在缓存中找到。
  • 返回值:成功时返回缓存内容,失败时返回 false。注意,由于 false 可能表示缓存未找到或存储值为 false,使用 $found 参数可以消除歧义。
  • 内部实现:函数调用全局 WP_Object_Cache 实例的 get() 方法,是 WordPress 对象缓存系统的核心接口。
  • 相关用途:广泛用于 WordPress 核心功能,如选项缓存、元数据检索、主题数据获取等,涉及多个文件和类。

代码示例

$value = wp_cache_get( 'wpdocs_mykey', 'wpdocs_mygroup', false, $found );

if ( ! $found ) {
    $value = wpdocs_my_expensive_function();
    wp_cache_set( 'wpdocs_mykey', $value, 'wpdocs_mygroup' );
}

return $value;

注意事项

  • 当缓存值可能为 false、null、0 或空数组等假值时,必须使用 $found 参数来区分缓存未命中和存储的假值,否则可能导致逻辑错误。
  • 某些缓存插件(如 WPEngine 的 dropins)可能未实现 $found 参数,导致其始终为 null。在这种情况下,应避免缓存 false 值,或使用替代值(如 0 或 null)并相应调整代码。
  • 函数自 WordPress 2.0.0 引入,是缓存操作的基础工具,开发者应确保在兼容环境中正确使用参数以优化性能。

📄 原文内容

Retrieves the cache contents from the cache by key and group.

Description

See also

Parameters

$keyint|stringrequired
The key under which the cache contents are stored.
$groupstringoptional
Where the cache contents are grouped. Default empty.
$forcebooloptional
Whether to force an update of the local cache from the persistent cache.

Default:false

$foundbool|nulloptional
Whether the key was found in the cache (passed by reference).
Disambiguates a return of false, a storable value.

Default:null

Return

mixed|false The cache contents on success, false on failure to retrieve contents.

Source

function wp_cache_get( $key, $group = '', $force = false, &$found = null ) {
	global $wp_object_cache;

	return $wp_object_cache->get( $key, $group, $force, $found );
}

Changelog

Version Description
2.0.0 Introduced.

User Contributed Notes

  1. Skip to note 5 content

    Here is how you use the $found parameter in your code – it is passed by reference, so you do not need to define the variable upfront, its value will be set by the called function instead:

    $value = wp_cache_get( 'wpdocs_mykey', 'wpdocs_mygroup', false, $found );
    
    if ( ! $found) {
        $value = wpdocs_my_expensive_function();
        wp_cache_set( 'wpdocs_mykey', $value, 'wpdocs_mygroup' );
    }
    
    return $value;

    You need to use the $found parameter if there is a slightest chance that the value you are caching can be zero, false, null, or otherwise equivalent to false (falsy) like an empty array.

    If you are not sure, or if you are looking for a general rule of thumb – always use the $found parameter.

    If some object caches are not implementing the $found parameter correctly, then that is a good reason to fix those implementations (or use better maintained ones) and not a reason to not use the parameter.

  2. Skip to note 6 content

    function prefix_get_post_count( $post_status = 'publish' ) {
        $cache_key = 'prefix_post_count_'. $post_status;
        $_posts = wp_cache_get( $cache_key );
        if ( false === $_posts ) {
            $_posts = $wpdb->get_var(
                        $wpdb->prepare(
                            "SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'post' AND post_status = %s",
                            $post_status
                        ));
     
            wp_cache_set( $cache_key, $_posts );
        }
     
        return $_posts;
    }

  3. Skip to note 7 content

    /**
     * Handles the users column output.
     *
     * @since 4.3.0
     *
     * @param array $blog Current site.
     */
    public function column_users( $blog ) {
        $user_count = wp_cache_get( $blog['blog_id'] . '_user_count', 'blog-details' );
        if ( ! $user_count ) {
            $blog_users = new WP_User_Query(
                array(
                    'blog_id'     => $blog['blog_id'],
                    'fields'      => 'ID',
                    'number'      => 1,
                    'count_total' => true,
                )
            );
            $user_count = $blog_users->get_total();
            wp_cache_set( $blog['blog_id'] . '_user_count', $user_count, 'blog-details', 12 * HOUR_IN_SECONDS );
        }
    
        printf(
            '<a href="%s">%s</a>',
            esc_url( network_admin_url( 'site-users.php?id=' . $blog['blog_id'] ) ),
            number_format_i18n( $user_count )
        );
    }

  4. Skip to note 8 content

    It seems some cache dropins (like those used on WPEngine) may define `wp_cache_get` WITHOUT the 4th parameter, `$found`. This means `$found` might not be populated by `wp_cache_get() ` (it will always be `null`, regardless of whether the value was cached or not), and you can also get a ton of warnings as reported here and here.

    The workaround? Pretend `$found` isn’t an argument, and never use `wp_cache_set() ` to cache a value of `false` (because you won’t be able to differentiate a cached value of `false` from the lack of a cached value, where `wp_cache_get() ` also returns `false`.)

    Eg
    [PHP]
    $result = wp_get_cache(‘my_key’);
    if( $result === false){
    // calculate the result, and use `0` or `null` instead of `false`
    if( $result === false){
    $result = 0;
    }
    wp_cache_set(‘my_key’, $result);
    }
    [/php]