aThemeArt

Preventing WordPress from Deleting a Post

At first look it seems as if there are not any hooks or filters in WordPress for preventing a post/page deletion. however you’ll be able to do it by filtering user_has_cap (short for user has capability). this can be a very powerful filter, and you’ll be able to use it to block virtually something in WordPress. it’s 3 parameters:

When a post is being deleted, $args is about to array (‘delete_post’, $user_id, $post_id). The capabilities needed to permit the deletion are held on within the array $caps, and can vary depending on what kind of post is being deleted (e.g. ‘delete_published_posts’). every capability in $caps corresponds to AN item in $allcaps. to stop the post being deleted, all we want to do is modify $allcaps by setting one in all the values listed in $caps to false (e.g. $allcaps[$caps[0]] = false).

As an example, the following code prevents the last published pages of a website being deleted.

  • $allcaps (an array of all the capabilities, each one set to true or false)
  • $caps ( An array of the capabilities being requested by the current operation )
  • $args (an array of arguments relevant to this operation).

add_filter ('user_has_cap', 'athemeart_prevent_last_page_deletion', 10, 3);
 
function athemeart_prevent_last_page_deletion ($allcaps, $caps, $args) {
    global $wpdb;
    if (isset($args[0]) && isset($args[2]) && $args[0] == 'delete_post') {
        $post = get_post ($args[2]);
        if ($post->post_status == 'publish' && $post->post_type == 'page') {
            $query = "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_status = 'publish' AND post_type = %s";
            $num_posts = $wpdb->get_var ($wpdb->prepare ($query, $post->post_type));
            if ($num_posts < 2)
                $allcaps[$caps[0]] = false;
        }
    }
    return $allcaps;
}

I hope you find this article helpful.

If you have any queries, ask us in the comment section below.

Inspire us with your love!

FacebookTwitterReddit
Avatar

Art of Awesome Professional WordPress themes & Site templates. Our responsive themes are designed to work seamlessly for all desktop and mobile devices. Modern, Clean & Easy To Use.

You can check also