使用clean_post_cache()函数清理WordPress中的帖子缓存
WordPress 中的clean_post_cache
功能用于清除特定帖子的缓存。当您想确保向用户显示帖子的最新版本时,此功能非常有用。
通过清除特定帖子的缓存,您可以确保帖子的任何更改或更新都会立即反映在网站前端。这对于包含大量动态内容或频繁更新的网站尤其重要。
clean_post_cache()基本语法
描述
WordPress PHP clean_post_cache()函数将清除缓存中的帖子
用法
clean_post_cache( $post_id );
$post
(int|WP_Post – 必需):您想要从缓存中删除的帖子 ID 或帖子对象
推荐:[最新版]YITH WooCommerce Social Login社交登录插件
clean_post_cache()函数
clean_post_cache() WordPress PHP 函数用于清除或删除缓存中的帖子。它还会清除与帖子 ID 关联的术语对象缓存。如果 $_wp_suspend_cache_invalidation 不为空,则此函数不会运行,可以使用 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' );
/**
* 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();
}
推荐: Enfold主题如何创建滑块
如何使用clean_post_cache()
清理单个帖子缓存,此代码用于清除ID为123的帖子的缓存。
$post_id = 123;
clean_post_cache( $post_id );
清理当前帖子的缓存,在循环中,您可以像这样清除当前帖子的缓存:
global $post;
clean_post_cache( $post->ID );
清理自定义帖子的缓存,对于自定义帖子类型,您可以执行以下操作:
$post_id = get_the_ID(); if ( 'custom_post_type' == get_post_type( $post_id ) ) { clean_post_cache( $post_id ); }
使用 clean_post_cache 清除特定帖子类型的所有帖子的缓存,此代码片段演示了如何使用 clean_post_cache 函数清除特定帖子类型(在本例中为“产品”帖子类型)的所有帖子的缓存
$post_type = 'product';
clean_post_cache( 0, get_post_type_object( $post_type )->name );
使用 clean_post_cache 清除特定分类法中所有帖子的缓存,此代码片段显示了如何使用 clean_post_cache 函数清除特定分类法(在本例中为“类别”分类法)中的所有帖子的缓存
$taxonomy = 'category';
clean_post_cache( 0, get_taxonomy( $taxonomy )->object_type );
更新帖子时清理缓存,如果您想在任何帖子更新时清除缓存,您可以使用save_post动作挂钩:
add_action( 'save_post', 'clean_post_cache' );
清理多篇帖子的缓存,如果你有一个帖子 ID 数组,并且想要清除所有帖子的缓存:在这些示例中,clean_post_cache()函数用于确保清除特定帖子的缓存,从而确保在下一个请求中提供最新的数据。
$post_ids = array( 123, 124, 125 );
foreach ( $post_ids as $post_id ) {
clean_post_cache( $post_id );
}
clean_post_cache
功能在维护 WordPress 网站的性能和效率方面起着至关重要的作用。通过清除特定帖子 ID 的缓存,此功能有助于确保始终为用户提供最新的内容,同时还可以减少服务器资源的压力。
与其他缓存机制(如插件或服务器端解决方案)结合使用时,该clean_post_cache
功能可以显著改善整体用户体验和网站速度。对于希望优化 WordPress 网站以获得更好性能的开发人员和网站管理员来说,这是一个很有价值的工具。通过了解如何有效地利用该clean_post_cache
功能,WordPress 用户可以利用其优势并为访问者提供更流畅、更高效的网站体验。
推荐:[最新版]WP Speed of Light Pro插件WordPress速度优化插件