Using WordPress ‘pre_delete_post’ PHP filter

pre_delete_post is a WordPress PHP filter that allows you to control whether a post deletion should take place or not.

Usage

add_filter('pre_delete_post', 'your_custom_function', 10, 3);

function your_custom_function($delete, $post, $force_delete) {
  // your custom code here
  return $delete;
}

Parameters

  • $delete (WP_Post|false|null) – Whether to go forward with deletion.
  • $post (WP_Post) – The post object to be deleted.
  • $force_delete (bool) – Whether to bypass the Trash.

More information

See WordPress Developer Resources: https://developer.wordpress.org/reference/hooks/pre_delete_post/

Examples

Prevent deletion of a specific post

Prevent deletion of a post with the ID of 42.

add_filter('pre_delete_post', 'prevent_specific_post_deletion', 10, 3);

function prevent_specific_post_deletion($delete, $post, $force_delete) {
  if ($post->ID == 42) {
    return false;
  }
  return $delete;
}

Disable force delete for all posts

Disable force delete and move all posts to Trash, even if $force_delete is set to true.

add_filter('pre_delete_post', 'disable_force_delete', 10, 3);

function disable_force_delete($delete, $post, $force_delete) {
  return $delete && !$force_delete;
}

Prevent deletion of posts with specific tag

Prevent deletion of posts tagged “important”.

add_filter('pre_delete_post', 'prevent_important_post_deletion', 10, 3);

function prevent_important_post_deletion($delete, $post, $force_delete) {
  if (has_tag('important', $post)) {
    return false;
  }
  return $delete;
}

Allow deletion only for admins

Allow post deletion only for administrators.

add_filter('pre_delete_post', 'allow_deletion_for_admins', 10, 3);

function allow_deletion_for_admins($delete, $post, $force_delete) {
  if (current_user_can('manage_options')) {
    return $delete;
  }
  return false;
}

Prevent deletion of published posts

Prevent deletion of posts that have a “publish” status.

add_filter('pre_delete_post', 'prevent_published_post_deletion', 10, 3);
function prevent_published_post_deletion($delete, $post, $force_delete) {
  if ($post->post_status == 'publish') {
    return false;
  }
  return $delete;
}