diff --git a/includes/activitypub/collection/class-event-sources.php b/includes/activitypub/collection/class-event-sources.php index b59ae15..649a683 100644 --- a/includes/activitypub/collection/class-event-sources.php +++ b/includes/activitypub/collection/class-event-sources.php @@ -208,6 +208,36 @@ class Event_Sources { delete_transient( 'event_bridge_for_activitypub_event_sources_ids' ); } + /** + * Check whether an attachment is set as a featured image of any post. + * + * @param string|int $attachment_id The numeric post ID of the attachment. + * @return bool + */ + public static function is_attachment_featured_image( $attachment_id ) { + if ( ! is_numeric( $attachment_id ) ) { + return false; + } + + // Query posts with the given attachment ID as their featured image. + $args = array( + 'post_type' => 'any', + 'meta_query' => array( + array( + 'key' => '_thumbnail_id', + 'value' => $attachment_id, + 'compare' => '=', + ), + ), + 'fields' => 'ids', // Only retrieve post IDs for performance. + 'numberposts' => 1, // We only need one match to confirm. + ); + + $posts = \get_posts( $args ); + + return ! empty( $posts ); + } + /** * Delete all posts of an event source. * @@ -242,10 +272,12 @@ class Event_Sources { if ( $thumbnail_id ) { // Remove the thumbnail from the post. - delete_post_thumbnail( $post->ID ); + \delete_post_thumbnail( $post->ID ); // Delete the attachment (and its files) from the media library. - wp_delete_attachment( $thumbnail_id, true ); + if ( self::is_attachment_featured_image( $thumbnail_id ) ) { + \wp_delete_attachment( $thumbnail_id, true ); + } } \wp_delete_post( $post->ID, true ); diff --git a/includes/activitypub/transmogrifier/class-base.php b/includes/activitypub/transmogrifier/class-base.php index d85f878..35bfd34 100644 --- a/includes/activitypub/transmogrifier/class-base.php +++ b/includes/activitypub/transmogrifier/class-base.php @@ -11,6 +11,7 @@ namespace Event_Bridge_For_ActivityPub\ActivityPub\Transmogrifier; use Activitypub\Activity\Extended_Object\Event; use DateTime; +use Event_Bridge_For_ActivityPub\ActivityPub\Collection\Event_Sources; use Exception; use WP_Error; @@ -150,8 +151,8 @@ abstract class Base { * * Forked from https://gist.github.com/kingkool68/a66d2df7835a8869625282faa78b489a. * - * @param int $post_id The post ID where the image will be set as featured image. - * @param string $url The image URL to maybe sideload. + * @param int $post_id The post ID where the image will be set as featured image. + * @param string $url The image URL to maybe sideload. * @uses media_sideload_image * @return string|int|WP_Error */ @@ -293,7 +294,7 @@ abstract class Base { $thumbnail_id = get_post_thumbnail_id( $post_id ); - if ( $thumbnail_id ) { + if ( $thumbnail_id && ! Event_Sources::is_attachment_featured_image( $thumbnail_id ) ) { wp_delete_attachment( $thumbnail_id, true ); }