Skip to content

Instantly share code, notes, and snippets.

@peterwilsoncc
Last active March 1, 2020 23:41
Show Gist options
  • Save peterwilsoncc/9148fd70572d9cc2a1c86e55ef88e251 to your computer and use it in GitHub Desktop.
Save peterwilsoncc/9148fd70572d9cc2a1c86e55ef88e251 to your computer and use it in GitHub Desktop.
<?php
namespace PWCC\AsyncDelete;
const ACTION_HOOK = 'pwcc.async_delete_post';
/**
* Register hooks for WordPress.
*/
function bootstrap() {
add_filter( 'pre_delete_post', __NAMESPACE__ . '\\async_delete_post', 10, 3 );
add_action( ACTION_HOOK, __NAMESPACE__ . '\\do_async_delete_post' );
}
bootstrap();
function async_delete_post( $pre, $post = 0, $force_delete ) {
// Allow for other preflight hooks, ensure post is set.
if ( $pre !== null || ! $post ) {
return $pre;
}
/*
* @TODO: consider if this should only happen for cron jobs, ie
* `wp_scheduled_delete` and `wp_scheduled_auto_draft_delete`.
*/
// If already running the async hook then avoid a loop.
if ( doing_action( ACTION_HOOK ) ) {
return $pre;
}
$post = get_post( $post );
$scheduled = wp_schedule_single_event(
time(),
ACTION_HOOK,
[
[
'post' => $post->ID,
'force_delete' => $force_delete,
],
]
);
return $scheduled ? $post : $pre;
}
function do_async_delete_post( $args ) {
wp_delete_post( $args['post'], $args['force_delete'] );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment