I am trying to delete a lot of WordPress posts programmatically using wp_delete_post, but not all posts are deleted successfully. In some cases I get NULL as a return value for wp_delete_post($row->post_id, true) and the post isn't deleted from the database.

There are both post and page post_types amongst those not deleted posts, as well as custom post types.

What can be the issue there, why aren't some posts deleted, while many others are deleted successfully?

  • Skimming wp_delete_post (and wp_trash_post, which is called for posts and pages but not custom types) and wp_delete_attachment, the only places they return null are when they can't find the post by ID e.g. here.
    – Rup
    Apr 12 at 11:10
  • Where are you getting the IDs from. Are you sure they exist? Apr 12 at 11:31
  • @JacobPeattie, those are posts of a specific language that I want to delete. I get them with get_posts function. And yes, I'm sure they exist in my wp_*_posts table. My WordPress is a multisite, so I have several wp_*_posts` tables. I am not sure if that matters, but anyway. Apr 12 at 11:37
  • 2
    If you're trying to delete posts from another site's posts table by ID, then that's not going to work. Apr 12 at 11:38

I realized that I was trying to delete a post while my current site wasn't the same one. My WordPress is multisite.

switch_to_blog($siteId); solved the issue.

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.