To clear all posts and their associated uploads in WordPress from your custom PHP script using wp-load.php, you can follow these steps:
Step 1: Include wp-load.php
Make sure your script has access to the WordPress environment by loading wp-load.php:
require_once('/path/to/your/wp-load.php');
Step 2: Delete Posts and Their Associated Data
You can loop through all posts, delete each post, and then remove any associated media files (attachments). Here's a complete script to achieve this:
'any', // 'any' retrieves all post types (posts, pages, custom post types)
'post_status' => 'any', // 'any' retrieves all post statuses
'posts_per_page' => -1, // Retrieve all posts
);
$all_posts = get_posts($args);
foreach ($all_posts as $post) {
// Get the post ID
$post_id = $post->ID;
// Check if the post has attachments (media files)
$attachments = get_attached_media('', $post_id);
// Delete each attachment associated with the post
foreach ($attachments as $attachment) {
$attachment_id = $attachment->ID;
// This deletes the file from the uploads directory and the database record
wp_delete_attachment($attachment_id, true);
}
// Delete the post itself
wp_delete_post($post_id, true); // true = force delete, bypass trash
}
echo 'All posts and their uploads have been deleted.';
Breakdown:
- Get all posts: The script retrieves all posts, pages, and custom post types.
- Get attachments: For each post, it checks if there are any attachments (media uploads like images or files).
- Delete attachments: It deletes each attachment using
wp_delete_attachment(), which also removes the file from the server. - Delete posts: Finally, the post itself is deleted using
wp_delete_post().
Step 3: Test Carefully
- Backup: Make sure you have a backup of your database and uploads folder before running this script.
- Use on a staging site: Test it on a staging environment before running on a live site, as it will permanently delete all posts and their uploads.
This script will ensure that both the posts and their associated media files are removed from the WordPress database and the filesystem.