0

I am building a plugin which in some cases prevents certain posts from being put into the bin. For this, I am using "wp_trash_post". In the callback function, I do the logic to check if the post can be put in the bin or not. If it can't then wp_die() is called. Simplified code looks like this:

add_action( 'wp_trash_post', 'check_delete_posts' );

function check_delete_posts( $post_id ) {
    $check = false;
    //Custom logic would go here to check if the post can't be put in the bin, setting $check to true    

    if( $check === true ) {
        wp_die( "You can't delete this post." );
    }

}

Now there is one case which I am having trouble with. The logic I added seems to work fine and bin posts which are supposed to and the wp_die message shows when the post can't be binned.

The issue is when the admin checks multiple posts (on the edit.php?post_type=my_custom_post_type screen) and then chooses "Move to Bin". Let's say for example the admin checks two posts, one which will pass the custom logic and one which will not, calling wp_die(). wp_die() will call correctly, however, when the user clicks back on their browser the edit screen will look exactly the same as before (even though now one post has been added to the bin). The user will have to refresh the page again until it shows the correct screen with one post in the bin.

In the wp_die() function I have tried setting the third argument to "true" to display a back link, but it has the same effect.

Is there any way to go back from wp_die() where it refreshes the edit screen as I expect?

Thanks in advance.

  • While this doesn't answer your question, I would use admin_notices instead of wp_die. Is there a reason you cannot use the core notices functionality? – Jared Cobb May 29 '17 at 17:24
  • Have a look at transition_post_status. I can't think of any action where halting execution is correct, I think you'll need to alter the status. – Milo May 29 '17 at 17:27
1

You should basically never dieon an action. It is likely to leave the system in unstable state.

The right way to solve your issue to to deny users from deleting the post by using the user_has_cap filter that enables you to override the default permissions users have. The added value is that users will (should) not be presented with the option to delete the post in the first place and/or the permission will be checked and operation denied before it is started.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.