Preventing frontpage to be deleted/moved to trash

I want to prevent my frontpage to be deleted/moved to trash using this:

add_action( 'wp_trash_post',      'tcb_page_delete_check' );
add_action( 'before_delete_post', 'tcb_page_delete_check' );
function tcb_page_delete_check( $post_id ){
    $frontpage = get_option( 'page_on_front');
    $blogpage = get_option('page_for_posts'); 
      if( $post_id === $frontpage || $post_id === $blogpage ) {
        wp_redirect(admin_url('edit.php?post_type=page'));
        exit;
      }
}

The problem is that option(‘page_on_front’)’s ID get’s changed from 7 (which is my desired frontpage ID) to 0 when I click on “Trash” so it never matches the frontpage ID and moves my page to trash.

And if I change it to:

    if( $post_id === 7 ...

The page does not get moved to trash but the option(‘page_on_front’)’s ID is changed to 0.

How do I prevent option(‘page_on_front’) to get changed to 0 so my frontpage stays the same and can’t get trashed?

1 Answer
1

There are two problems with your code snippet:

1) Comparison

The first problem is in this line:

  if( $post_id === $frontpage || $post_id === $blogpage ) {

where you’re strictly comparing int with string.

Notice that === comparison will only return TRUE if both variables are of the same type and have the same value.

Try this instead:

  if( $post_id == $frontpage || $post_id == $blogpage ) {

where == will perform a type conversion, or simply use the (int) typecasting:

  if( $post_id === (int) $frontpage || $post_id === (int) $blogpage ) {

You could also use intval().

2) Priority

The second problem is the callback priority. You should run your callbacks earlier, for example, with priority 1 instead of the default 10:

add_action( 'wp_trash_post',      'tcb_page_delete_check', 1 );
add_action( 'before_delete_post', 'tcb_page_delete_check', 1 );

Hope this helps.

Leave a Comment