jon-c
4/5/2018 - 8:53 PM

Clear some WP Super Cache files when any post is saved

Clear some WP Super Cache files when any post is saved

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