Prevent users from deleting a page or post in WordPress

During my time developing plugins, theme and sites using WordPress I have often come across the need
to prevent certain pages from being deleted. I have tried many solutions that did not do the trick or
didn’t provide a full solution to the problem. Some left the delete links but would create errors
when they were clicked for instance.

The following function will allow you to prevent any user including admins from deleting a specific
page, post or custom post type item. Not only that but it also prevents the trash & delete links
from appearing anywhere for that post. It will also prevent trashing the item during mass deletions.

You can set the $post_id anyway you see fit. Use a site_option, an array of ids via in_array() etc.

Daniel Iser is a professional WordPress plugin developer, and the author of plugins such as Easy Modal & Popup Maker. Founder of Wizard Internet Solutions he has been working with WordPress for over 7 years creating websites and tools for clients & blog authors.

Follow on:

3 Comments

  1. Marx on May 17, 2020 at 1:53 pm

    Hey, great. This one gives me no errors and works but how can I have multiple page ids? Like nested array or something?

    • danieliser on May 18, 2020 at 9:58 pm

      You would simply need to loop over an array of post IDs and compare them instead of checking one specific one.

          $post_ids = [1,2,3];
      
          if ( isset( $args[0] ) && isset( $args[2] ) && in_array( $args[2], $post_ids ) && $args[0] == 'delete_post' ) {
              $allcaps[ $caps[0] ] = false;
          }
      • Marx on May 20, 2020 at 9:23 am

        Perfect, thank you so much 🙂

Leave a Comment





This site uses Akismet to reduce spam. Learn how your comment data is processed.