bool wp_cache_add ( int|string $key, mixed $data [, string $flag [, int $expire ]] )
This function is part of the WP Cache system. Its function is to add data to the cache, if the cache key doesn't already exist.
For examples of how to use this function, see the Examples section below.
This function uses PHP function style parameters.
The function returns true on success and false if the cache ID and group already exists.
Placeholder section that would be used with functions that return WP Error objects.
Version | Description |
---|---|
2.5 | $data filtering is removed. |
2.1.1 | $data is filtered through first serialize() and then unserialize(). |
2.0.0 | Added to WordPress core. |
There are many examples throughout WordPress' core that use this function. Below are a couple of code selections.
The Function Reference/Category API shows a very good example of using wp_cache_add() in combination with wp_cache_get() to ensure that the expensive queries and data processing to gather all the category IDs only occur once.
Note: The following code was taken from wp-includes/category.php version 2.7.
<?php
function get_all_category_ids() {
if ( ! $cat_ids = wp_cache_get( 'all_category_ids', 'category' ) ) {
$cat_ids = get_terms( 'category', 'fields=ids&get=all' );
wp_cache_add( 'all_category_ids', $cat_ids, 'category' );
}
return $cat_ids;
}
?>
The code that displays the Recent Entries widget provides a good example of how much code can be skipped by using caching.
Note: The following code was taken from wp-includes/widgets.php version 2.7.
<?php
function wp_widget_recent_entries($args) {
if ( '%BEG_OF_TITLE%' != $args['before_title'] ) {
if ( $output = wp_cache_get('widget_recent_entries', 'widget') )
return print($output);
ob_start();
}
extract($args);
$options = get_option('widget_recent_entries');
$title = empty($options['title']) ? __('Recent Posts') :
apply_filters('widget_title', $options['title']);
if ( !$number = (int) $options['number'] )
$number = 10;
else if ( $number < 1 )
$number = 1;
else if ( $number > 15 )
$number = 15;
$r = new WP_Query(array('showposts' => $number, 'what_to_show' => 'posts',
'nopaging' => 0, 'post_status' => 'publish', 'caller_get_posts' => 1));
if ($r->have_posts()) :
?>
<?php echo $before_widget; ?>
<?php if ( !empty( $title ) ) { echo $before_title . $title . $after_title; } ?>
<ul>
<?php while ($r->have_posts()) : $r->the_post(); ?>
<li><a href="<?php the_permalink() ?>">
<?php if ( get_the_title() ) the_title(); else the_ID(); ?>
</a></li>
<?php endwhile; ?>
</ul>
<?php echo $after_widget; ?>
<?php
wp_reset_query(); // Restore global post data stomped by the_post().
endif;
if ( '%BEG_OF_TITLE%' != $args['before_title'] )
wp_cache_add('widget_recent_entries', ob_get_flush(), 'widget');
}
?>