Delete WordPress Posts with Images

User
Delete all posts with image custom wordpress
Assistant
To delete all posts with images in WordPress, you can use a custom script. WordPress stores image attachments as post types (`attachment`) and links them to their parent posts via the `post_parent` field. You can filter and delete posts based on whether they have associated images.

Here's how you can do it safely:

### Method 1: Using a Custom PHP Script
Add the following code to your **theme's functions.php** file or create a custom plugin. Ensure you have a backup of your database before proceeding.

function delete_posts_with_images() {
    // Query posts with images
    $args = [
        'post_type'      => 'post',
        'posts_per_page' => -1,
        'meta_query'     => [
            [
                'key'     => '_thumbnail_id', // Checks for a featured image
                'compare' => 'EXISTS',
            ],
        ],
    ];
    
    $query = new WP_Query($args);

    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();

            // Delete the post
            wp_delete_post(get_the_ID(), true);
        }
    }

    // Restore global post data
    wp_reset_postdata();
}

// Hook this function to a specific action (e.g., admin_init or init)
add_action('admin_init', 'delete_posts_with_images');

### Explanation
1. **`_thumbnail_id` Meta Key**: This checks if the post has a featured image.
2. **`wp_delete_post`**: Deletes the post and its associated data.
3. **`true` Parameter in `wp_delete_post`**: Ensures the post is forcefully deleted (skips trash).

### Method 2: Using SQL Query (Direct Database Update)
If you're comfortable working directly with the database, you can run a query to delete posts that have images.

#### SQL Query

DELETE p
FROM wp_posts p
JOIN wp_postmeta pm
    ON p.ID = pm.post_id
WHERE pm.meta_key = '_thumbnail_id'
  AND p.post_type = 'post';

#### Steps:
1. Backup your database.
2. Run the query in **phpMyAdmin** or your database management tool.

### Notes:
– Always test on a staging environment first.
– Backup your database to prevent data loss.
– If you only want to delete drafts or specific posts, modify the query accordingly.

Leave a Comment

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