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.
'numberposts'=>-1
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.
Unbelievable! Your solution works great!Thank you very much, Saruque!
I am glad that it helped you. Keep visiting our site and happy coding.
Hi Saruque. Is it possible to use a similar script to yours above to bulk delete all draft products? I tried your code in functions.php and replaced ‘product’ with ‘draft’ but the 4 test products I have in draft are still there. As you can tell, coding is not my expertise!
Hi. Sorry for the newbie question. Where do I place this code? Do I use Code Snippets?
Thank you in advance.