Skip to content

Instantly share code, notes, and snippets.

@daviddarke
Created November 22, 2017 15:33
Show Gist options
  • Save daviddarke/60b472cd85fefbdd44e9a4971a58a64a to your computer and use it in GitHub Desktop.
Save daviddarke/60b472cd85fefbdd44e9a4971a58a64a to your computer and use it in GitHub Desktop.
Clear CPT archives when a CPT single is created or updated
$custom_post_types = array( "my_post" => "my_post");
$max_archive_pages = 0; // 0 == all archive page #s
function post_status( $new_status, $old_status, $post )
{
global $custom_post_types, $max_archive_pages;
if ( array_key_exists( $post->post_type, $custom_post_types ) && ( $new_status === "publish" || $old_status === "publish" ) )
{
if ( defined( 'W3TC' ) )
{
$archive = empty( trim( $custom_post_types[$post->post_type] ) ) ? $post->post_type:trim( $custom_post_types[$post->post_type] );
$post->post_status = "";
$link = preg_replace( '~__trashed/$~', '/', get_permalink( $post ) );
w3tc_flush_url( $link );
$posts_per_page = get_option( 'posts_per_page' );
$posts_number = \W3TC\Util_PageUrls::get_archive_posts_count( 0, 0, 0, $post->post_type );
$posts_pages_number = @ceil( $posts_number / $posts_per_page );
if ( $max_archive_pages > 0 && $posts_pages_number > $max_archive_pages ) {
$posts_pages_number = $max_archive_pages;
}
if ( $posts_pages_number == 0 ) {
w3tc_flush_url( \W3TC\Util_Environment::home_domain_root_url() . "/" . $archive );
} else {
for ( $pagenum = 1; $pagenum <= $posts_pages_number; $pagenum++ ) {
$link = \W3TC\Util_PageUrls::get_pagenum_link( $archive, $pagenum );
w3tc_flush_url( $link );
}
}
}
}
}
add_action( 'transition_post_status', 'post_status', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment