Skip to content

Instantly share code, notes, and snippets.

@david-binda
Last active January 28, 2016 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save david-binda/d7d7daa5128bd5f0bebc to your computer and use it in GitHub Desktop.
Save david-binda/d7d7daa5128bd5f0bebc to your computer and use it in GitHub Desktop.
Asynchronous term object cache clearing for cases when term update times out.
<?php
//disable cache invalidation just before the term objects cache is cleared
function my_prefix_deactivate_cache_invalidation( $tt_id, $taxonomy ) {
//wp_suspend_cache_invalidation returns current status before it get's changed
$current_cache_suspend_status = wp_suspend_cache_invalidation( true );
//schedule asynchronous cache clearing
wp_schedule_single_event( time(), 'my_prefix_invalidate_term_objects_cache', array( $tt_id, $taxonomy ) );
//if cache invalidation was not previously deactivated, we need to reactivate it
//neds to check for `true !==` as `wp_suspend_cache_invalidation` returns null in case it was not called previously
if ( true !== $current_cache_suspend_status ) {
add_action( 'edit_term', 'my_prefix_reactivate_cache_invalidation' );
}
}
add_action( 'edited_term_taxonomy', 'my_prefix_deactivate_cache_invalidation', 10, 2 );
//re-activate cache invalidation
function my_prefix_reactivate_cache_invalidation() {
wp_suspend_cache_invalidation( false );
}
//Cron triggered function which actually cleans the cache
function my_prefix_invalidate_term_objects_cache( $tt_id, $taxonomy ) {
global $wpdb;
$objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) );
$tax_object = get_taxonomy( $taxonomy );
foreach ( $tax_object->object_type as $object_type ) {
clean_object_term_cache( $objects, $object_type );
}
}
add_action( 'my_prefix_invalidate_term_objects_cache', 'my_prefix_invalidate_term_objects_cache', 10, 2 );
@david-binda
Copy link
Author

This works only when following patch is in place: https://core.trac.wordpress.org/attachment/ticket/28743/taxonomy.php.patch

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment