• I wrote a cron job to delete revisions for posts older than 4 weeks, and then remove any unattached media.

    // delete old revisions
    	global $wpdb;
    	$num1 = $wpdb->query("DELETE FROM ".$wpdb->posts." WHERE post_type = 'revision'");
    	// clean orphaned post meta.
    	$num2 = $wpdb->query("DELETE pm FROM ".$wpdb->postmeta." pm LEFT JOIN ".$wpdb->posts." p ON pm.post_id = p.ID WHERE p.ID IS NULL");
    	// delete unattached attachments (images & videos not referenced in any posts)
    	$attachments = get_posts([
    		"post_type" => "attachment",
    		"numberposts" => -1,
    		"post_parent" => 0,
    		"fields" => "ids",
    	]);
    	foreach ($attachments as $id) {
    		wp_delete_attachment($id, true);
    	}

    But unfortunately, attachments that only exist in a revision remain but really have no reference in the post content.

    The attachments still retain a parent_post value of the published post, and there is no apparently easy way to detect if the attachment is contained within the post.

    So now I have a load of attachements relating to posts which actually do not reference them in the content.

    How do I know which ones are actually referenced in the post besides parsing the content?
    I’m 99% sure of the answer but just want to check that there isn’t a better solution.

    • This topic was modified 3 years, 7 months ago by hedgehog90.
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
  • The topic ‘Removing all Media attached to a deleted revision’ is closed to new replies.