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?
There are two problems with your code snippet:
1) Comparison
The first problem is in this line:
where you’re strictly comparing
int
withstring
.Notice that
===
comparison will only returnTRUE
if both variables are of the same type and have the same value.Try this instead:
where
==
will perform a type conversion, or simply use the(int)
typecasting: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 default10
:Hope this helps.