How to prevent a WordPress page from being deleted by a user

Some WordPress plugins create a page or a post, and proper function of the plugin relies on the existence of that page or post. For example, a plugin that manages an e-mail list might rely on an unsubscribe page, which a user might delete on purpose or by accident.

How can a plugin prevent its page from being deleted?

Related posts

Leave a Reply

2 comments

  1. First, when you create the page, you can store its ID in an option that you need to get later:

    add_option('undeleteable_page_id', $the_page_id, '', 'no'); // 'no' so this option does not load on every page
    

    Then, you hook into the delete actions with functions to prevent the deletion:

    add_action('deleted_post', 'prevent_undeleteable_page_deletion');
    add_action('trashed_post', 'prevent_undeleteable_page_trash');
    

    In those functions, you check the id of the page being deleted and compare it to the id that you stored when you created the page.

    if($id == get_option('undeleteable_page_id')) ...
    

    In the “prevent trash” function, you change the status back to publish.
    In the prevent deletion function, you re-create the page.

    This is how I did this, and it worked for me. I would love to see how others may have approached this problem.