Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

User:Chrisbliss18/wp cache add

This article is a ROUGH DRAFT. The author is still working on this document, so please do not edit this without the author's permission. The content within this article may not yet be verified or valid. This information is subject to change.

Description

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.

Parameters

This function uses PHP function style parameters.

key
The cache ID to use for retrieval later. This is a required parameter.
data
The data to add to the cache store. This is a required parameter.
flag
The group to add the cache to. Default value is an empty string.

It should be noted that the default value for this parameter in both WP_Object_Cache::add() and WP_Object_Cache::set() is default rather than an empty string. This editor does not know if this difference was an oversight or intentional.
expire
When the cache data should expire. Default value is 0.

Tracing this variable through the resulting call to WP_Object_Cache::set(), it can be seen that this parameter is not used. This may just be a placeholder for future functionality.

Return Values

The function returns true on success and false if the cache ID and group already exists.

Errors/Exceptions

Placeholder section that would be used with functions that return WP Error objects.

ChangeLog

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.

Examples

There are many examples throughout WordPress' core that use this function. Below are a couple of code selections.

Retrieving All Category IDs

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;
}
?>

Display Recent Entries Widget

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 )
        
$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');
}
?>

Notes

  • This function uses PHP function style parameters.
  • wp_cache_add() is a wrapper that calls $wp_object_cache->add(...). See the WP_Object_Cache::add() function code for details on how this code operates.

See Also


Limitations While Creating This Document

  • A rule in the Codex's CSS prevents DIVs from being styled. I worked around this by using SPANs with a display of block.
  • The CSS rules don't have any padding for table elements. The only way to work around this (due to not being able to define CSS rules other than via individual style declarations) is by either using cellspacing and cellpadding (not desirable) or adding style information to every TH and TD element (also not desirable).
  • Lack of styling for DD and DT elements. I solved this by manually applying style information to each element.
  • The </dd> and </dt> elements are not supported, thus breaking standards.
  • The %%% directive makes very nicely-colored PHP code output, but it has limitations.
    • To get the output to be have syntax highlighting, it needs to be wrapped in <?php ?> tags. This adds unnecessary lines since the presence of these tags can be assumed in most instances. It would be nice if there could be an option to force highlighting without the use of the tags.
    • The output contains large amounts of whitespace at the top and bottom.
    • The output is not contained in a box like as the CSS styles the PRE. This type of container is helpful as it clearly sets the code apart from the rest of the documentation. I manually applied this look using the styled SPAN that I used for the function structure.