How to delete all posts from a custom post type in WordPress

Hello developers, I am here again to provide you very essential as well as a useful code snippet. I have found people deleting posts of a custom type using plugins or complicated database commands. But here I am gonna show you the easiest way to delete all posts of a custom post type without using plugins. So let’s see how to do that

How to create custom WordPress shortcode?

Delete all posts of a custom post type in WordPress without database commands

Before going to show you how to delete just consider that you have a custom post type.

and the post type is product 

It can be anything, I am just showing you with an example.

To delete all the posts from this custom post type you need to take a variable first.

$allposts= get_posts( array('post_type'=>'product','numberposts'=>-1) );
foreach ($allposts as $eachpost) {
  wp_delete_post( $eachpost->ID, true );

These three lines of code are enough to achieve our goal.

Now it’s time to explain what I have done.

How to remove the website field from WordPress comment?

At first, we need to take a variable to get all the posts in it. We took $allposts variable here

Then we have used get_posts() method which is an inbuilt method of WordPress.

In that array we have passed ‘post_type’=>’product’. Remember product is our custom post type. You need to use the exact post type which is set under register_post_type.


It is defined to -1 because -1 is for all the posts. and we want to get all the posts here.

Now Finally we have used a foreach loop to go through each post and delete all.

wp_delete_post( $eachpost->ID, true );

this is a WordPress function to delete posts. The first parameter is for the post ID. But here as $eachpost is an object so we need to use  $eachpost->ID to get the ID.

Add a custom widget area for custom WordPress theme Theme development

We need to set the second parameter true to delete the posts.

Leave a Reply

Your email address will not be published. Required fields are marked *