函数文档

clean_post_cache()

💡 云策文档标注

概述

clean_post_cache() 函数用于从缓存中清理指定文章的数据,包括文章对象、元数据和相关分类术语缓存。该函数在 $_wp_suspend_cache_invalidation 不为空时不会执行。

关键要点

  • 清理缓存包括删除 posts、post_meta 和 post_parent 缓存条目,以及调用 clean_object_term_cache() 清理相关术语缓存。
  • 函数接受文章 ID 或 WP_Post 对象作为参数,并会触发 clean_post_cache 和 clean_page_cache(针对页面类型)钩子。
  • 执行前会检查 $_wp_suspend_cache_invalidation 全局变量,若不为空则直接返回,避免缓存无效化。

代码示例

function clean_post_cache( $post ) {
	global $_wp_suspend_cache_invalidation;

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

	$post = get_post( $post );

	if ( ! $post ) {
		return;
	}

	wp_cache_delete( $post->ID, 'posts' );
	wp_cache_delete( 'post_parent:' . (string) $post->ID, 'posts' );
	wp_cache_delete( $post->ID, 'post_meta' );

	clean_object_term_cache( $post->ID, $post->post_type );

	wp_cache_delete( 'wp_get_archives', 'general' );

	do_action( 'clean_post_cache', $post->ID, $post );

	if ( 'page' === $post->post_type ) {
		wp_cache_delete( 'all_page_ids', 'posts' );
		do_action( 'clean_page_cache', $post->ID );
	}

	wp_cache_set_posts_last_changed();
}

注意事项

  • 该函数自 WordPress 2.0.0 版本引入,常用于文章更新、删除或状态变更时维护缓存一致性。
  • 相关函数包括 wp_cache_delete()、clean_object_term_cache() 和 do_action(),确保在开发插件或主题时正确调用以避免缓存问题。

📄 原文内容

Will clean the post in the cache.

Description

Cleaning means delete from the cache of the post. Will call to clean the term object cache associated with the post ID.

This function not run if $_wp_suspend_cache_invalidation is not empty. See wp_suspend_cache_invalidation() .

Parameters

$postint|WP_Postrequired
Post ID or post object to remove from the cache.

Source

function clean_post_cache( $post ) {
	global $_wp_suspend_cache_invalidation;

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

	$post = get_post( $post );

	if ( ! $post ) {
		return;
	}

	wp_cache_delete( $post->ID, 'posts' );
	wp_cache_delete( 'post_parent:' . (string) $post->ID, 'posts' );
	wp_cache_delete( $post->ID, 'post_meta' );

	clean_object_term_cache( $post->ID, $post->post_type );

	wp_cache_delete( 'wp_get_archives', 'general' );

	/**
	 * Fires immediately after the given post's cache is cleaned.
	 *
	 * @since 2.5.0
	 *
	 * @param int     $post_id Post ID.
	 * @param WP_Post $post    Post object.
	 */
	do_action( 'clean_post_cache', $post->ID, $post );

	if ( 'page' === $post->post_type ) {
		wp_cache_delete( 'all_page_ids', 'posts' );

		/**
		 * Fires immediately after the given page's cache is cleaned.
		 *
		 * @since 2.5.0
		 *
		 * @param int $post_id Post ID.
		 */
		do_action( 'clean_page_cache', $post->ID );
	}

	wp_cache_set_posts_last_changed();
}

Hooks

do_action( ‘clean_page_cache’, int $post_id )

Fires immediately after the given page’s cache is cleaned.

do_action( ‘clean_post_cache’, int $post_id, WP_Post $post )

Fires immediately after the given post’s cache is cleaned.

Changelog

Version Description
2.0.0 Introduced.