Halloween Sale 15% off Ends in See the plans
PHP

Clear Related Pages From WP Rocket's Cache on Update

When a post is updated, also clears the WP Rocket cache for the homepage, the blog page, its category and tag archives and the author page, so lists never show stale titles or excerpts.

Don’t have WPIDE yet? Install it on your site

Code

$wpide_extra_urls = array(); // e.g. array( home_url( '/news/' ) ).

add_action( 'transition_post_status', function ( $new, $old, $post ) use ( $wpide_extra_urls ) {
    if ( ! function_exists( 'rocket_clean_files' ) || ( 'publish' !== $new && 'publish' !== $old ) || wp_is_post_revision( $post ) || ! is_post_type_viewable( $post->post_type ) ) {
        return;
    }

    $urls = $wpide_extra_urls;
    $urls[] = home_url( '/' );

    if ( 'post' === $post->post_type && get_option( 'page_for_posts' ) ) {
        $urls[] = get_permalink( (int) get_option( 'page_for_posts' ) );
    }

    foreach ( get_object_taxonomies( $post->post_type ) as $taxonomy ) {
        if ( ! is_taxonomy_viewable( $taxonomy ) ) {
            continue;
        }
        foreach ( (array) wp_get_post_terms( $post->ID, $taxonomy ) as $term ) {
            $link = get_term_link( $term );
            if ( ! is_wp_error( $link ) ) {
                $urls[] = $link;
            }
        }
    }

    $urls[] = get_author_posts_url( (int) $post->post_author );

    rocket_clean_files( array_values( array_unique( array_filter( $urls ) ) ) );
}, 20, 3 );

Notes

Does nothing unless WP Rocket is active. Add extra URLs to $wpide_extra_urls, such as a landing page that lists posts.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.