函数文档

clean_attachment_cache()

💡 云策文档标注

概述

clean_attachment_cache() 函数用于清理附件缓存,包括从 posts 和 post_meta 缓存组中删除指定附件 ID 的数据。可选清理关联的术语对象缓存,并在特定条件下跳过执行。

关键要点

  • 函数清理指定附件 ID 的缓存,包括 posts 和 post_meta 缓存组。
  • 可选参数 $clean_terms 控制是否清理关联的术语对象缓存,默认值为 false。
  • 如果全局变量 $_wp_suspend_cache_invalidation 不为空,函数将不执行任何操作。
  • 函数执行后会触发 clean_attachment_cache 动作钩子。

代码示例

function clean_attachment_cache( $id, $clean_terms = false ) {
	global $_wp_suspend_cache_invalidation;

	if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
		return;
	}

	$id = (int) $id;

	wp_cache_delete( $id, 'posts' );
	wp_cache_delete( $id, 'post_meta' );

	if ( $clean_terms ) {
		clean_object_term_cache( $id, 'attachment' );
	}

	do_action( 'clean_attachment_cache', $id );
}

注意事项

  • 确保在调用前检查 $_wp_suspend_cache_invalidation 状态,以避免不必要的缓存操作。
  • 清理术语缓存可能影响性能,建议仅在需要时启用 $clean_terms 参数。

📄 原文内容

Will clean the attachment in the cache.

Description

Cleaning means delete from the cache. Optionally will clean the term object cache associated with the attachment ID.

This function will not run if $_wp_suspend_cache_invalidation is not empty.

Parameters

$idintrequired
The attachment ID in the cache to clean.
$clean_termsbooloptional
Whether to clean terms cache.

Default:false

Source

function clean_attachment_cache( $id, $clean_terms = false ) {
	global $_wp_suspend_cache_invalidation;

	if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
		return;
	}

	$id = (int) $id;

	wp_cache_delete( $id, 'posts' );
	wp_cache_delete( $id, 'post_meta' );

	if ( $clean_terms ) {
		clean_object_term_cache( $id, 'attachment' );
	}

	/**
	 * Fires after the given attachment's cache is cleaned.
	 *
	 * @since 3.0.0
	 *
	 * @param int $id Attachment ID.
	 */
	do_action( 'clean_attachment_cache', $id );
}

Hooks

do_action( ‘clean_attachment_cache’, int $id )

Fires after the given attachment’s cache is cleaned.

Changelog

Version Description
3.0.0 Introduced.