wp_cache_set( int|string $key, mixed $data, string $group = , int $expire ): bool

Saves the data to the cache.


Differs from wp_cache_add() and wp_cache_replace() in that it will always write data.

See also


The cache key to use for retrieval later.
The contents to store in the cache.
Where to group the cache contents. Enables the same key to be used across groups.


When to expire the cache contents, in seconds.
Default 0 (no expiration).


bool True on success, false on failure.


function wp_cache_set( $key, $data, $group = '', $expire = 0 ) {
	global $wp_object_cache;

	return $wp_object_cache->set( $key, $data, $group, (int) $expire );



User Contributed Notes

  1. Skip to note 3 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(
                            "SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'post' AND post_status = %s",
            wp_cache_set( $cache_key, $_posts );
        return $_posts;
  2. Skip to note 4 content

    Requests made to third-party endpoints should be cached, regardless of being synchronous or asynchronous. Not doing so will result in your site’s load time depending on an unreliable API response!

     * Retrieve posts from another blog and cache the response body.
     * @return   string   Body of the response. Empty string if no body or incorrect parameter given.
    function wpdocs_get_posts_from_other_blog() {
        $posts = wp_cache_get( 'wpdocs_other_blog_posts' );
        if ( false === $posts ) {
            $request = wp_remote_get( 'https://jsonplaceholder.typicode.com/posts' );
            $posts = wp_remote_retrieve_body( $request );
            wp_cache_set( 'wpdocs_other_blog_posts', $posts, '', HOUR_IN_SECONDS );
        return $posts;

You must log in before being able to contribute a note or feedback.