Halloween Sale 15% off Ends in See the plans
PHP

Protect Important Pages From Deletion

Stops anyone, administrators included, from trashing or deleting the homepage, blog page, privacy page and any other pages you list.

Don’t have WPIDE yet? Install it on your site

Code

// Extra page or post IDs to protect, besides the homepage, posts page and privacy policy page.
$wpide_protected_ids = array();

add_filter( 'map_meta_cap', function ( $caps, $cap, $user_id, $args ) use ( $wpide_protected_ids ) {
    if ( ! in_array( $cap, array( 'delete_post', 'delete_page' ), true ) || empty( $args[0] ) ) {
        return $caps;
    }

    $protected = array_merge(
        $wpide_protected_ids,
        array(
            (int) get_option( 'page_on_front' ),
            (int) get_option( 'page_for_posts' ),
            (int) get_option( 'wp_page_for_privacy_policy' ),
        )
    );

    if ( in_array( (int) $args[0], array_filter( array_map( 'intval', $protected ) ), true ) ) {
        $caps[] = 'do_not_allow';
    }

    return $caps;
}, 10, 4 );

Notes

To delete a protected page later, change the Reading settings first or deactivate the snippet.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.