Created
April 5, 2018 20:53
-
-
Save jondcampbell/fd5c38503818652c87f9f1f0cc553f83 to your computer and use it in GitHub Desktop.
Clear some WP Super Cache files when any post is saved
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Functionality for managing WP Super Cache | |
*/ | |
/** | |
* On post save | |
* | |
* @param int $post_id the post id of the post being saved. | |
*/ | |
function pec_cache_post_saved( $post_id ) { | |
// If we aren't looking at posts skip out. | |
if ( get_post_type( $post_id ) != 'post' ) { | |
return; | |
} | |
// If the super cache function doesn't exist skip out. | |
if ( ! function_exists( 'wpsc_delete_files' ) ) { | |
return; | |
} | |
$url = get_permalink( $post_id ); | |
// Clear the cache for the post itself. | |
pec_cache_clear_url( $url ); | |
// Find the categories for this post. | |
$post_cats = get_the_category( $post_id ); | |
foreach ( $post_cats as $category ) { | |
$category_link = get_category_link( $category->term_id ); | |
// Clear each category cache. | |
pec_cache_clear_url( $category_link ); | |
} | |
// Clear the homepage cache by passing in the site url WITH the trailing slash. | |
pec_cache_clear_url( trailingslashit( site_url() ) ); | |
} | |
add_action( 'save_post', 'pec_cache_post_saved' ); | |
/** | |
* Clear the cache for a path | |
* | |
* @param url $full_url the whole url we want to clear the cache of. | |
* | |
* @return bool | |
*/ | |
function pec_cache_clear_url( $full_url ) { | |
$path = wp_parse_url( $full_url, PHP_URL_PATH ); | |
$file_path = realpath( trailingslashit( get_supercache_dir() . str_replace( '..', '', preg_replace( '/:.*$/', '', strtolower( $path ) ) ) ) ) . '/'; | |
if ( '/' === $file_path ) { | |
return false; // Directory not found. Probably not cached. | |
} else { | |
wpsc_delete_files( $file_path ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment