Prevent Trashing of the Static Home Page in WordPress

WordPress - home page When I was working on my custom caching script, one of my functions wouldn’t work correctly if I accidentally trashed the static home page. The solution was to remove the ability to trash it.

The proper way to replace a static home page in WordPress is to assign a different page and then trash the old home page (if necessary). If you trash it before the reassignment, it will set the default posts page as the home page until you change it again. It may not seem like a big deal, but it is when a script depends on it.

Prevent Trashing of the Static Home Page

All I really needed to do was to keep myself from trashing the static home page by accident. I could have figured it out by myself, but I found a function on a website that no longer resolves and tested it before putting it to use. It uses the WordPress user_has_cap filter:

function user_cap_filter( $allcaps, $cap, $args ) {
  if ( 'delete_post' == $args[0] ) {
    if ( get_option( 'page_on_front' ) == $args[2] ) {
      $allcaps[$cap[0]] = false;
    }
  }
  return $allcaps;
}
add_filter( 'user_has_cap', 'user_cap_filter', 10, 3 );

Once this function is active, the option to move the static home page to the trash is no longer available anywhere, so it’s impossible to trash it without doing it manually in the database. It removes the link on the edit screen and the post listing screen and probably in other places I wouldn’t normally look.

I think this function to prevent trashing of the static home page is just as important for other WordPress site owners as it is for me, otherwise I wouldn’t bother to write about it. I have a lot of little functions that I should pass on, but remembering which one is which eludes me until I see them again.

If I stumble upon another function I’ve written, which I think is as important as this one, I’ll be to sure to publish it before I forget about it again.

Share this: