If you need to move all WordPress posts to trash, you can use a custom function and the wp_trash_post
function to do so. In this post, we’ll walk through the steps to create a function that loops through all posts and then trashes all posts. And then hook it to an action so that it executes when needed. This is a quick and easy way to clear out old posts.
- Create a custom function that retrieves all posts and trashes them using the
wp_trash_post
function:
function trash_all_posts() {
$posts = get_posts(array(
'numberposts' => -1,
'post_status' => 'any',
'post_type' => 'post'
));
foreach($posts as $post) {
wp_trash_post($post->ID);
}
}
- Hook the function to an action. For example, you can hook it to the
wp_footer
action:
add_action('wp_footer', 'trash_all_posts');
This will execute the trash_all_posts
function whenever the wp_footer
action is triggered.
Keep in mind that trashing a WordPress post moves it to the trash bin, but it doesn’t delete it permanently. To delete the posts permanently, you’ll need to use the wp_delete_post
function instead. For more library functions you can refer to wp codex.
Whether you’re cleaning up your site or preparing for a redesign, this technique can save you time and effort.