Remove image files when deleting ads

We provide the code snippets and content on this page without any guarantee or support. In most cases, these pages are created on requests or based on individual solutions sent to us by other users. After it was published, we are only reviewing the code and content when we are made aware of an issue. Please let us know if you find one.

Please only use the codes if you understand them and know how to add custom code to your WordPress site.

The following solution addresses the need to automatically delete image files associated with ads from your media library. To enable the automatic deletion of a media image linked to an ad unit upon deletion, add the following code snippet to the functions.php file.

add_action( 'before_delete_post', 'delete_ad_image', 99, 2 );

function delete_ad_image( $post_id, $post ) {
    if ( $post->post_type !== 'advanced_ads' ) {
        return;
    }

    if ( EMPTY_TRASH_DAYS && $post->post_status !== 'trash' ) {
        return;
    }

    $ad_options = get_post_meta( $post_id, 'advanced_ads_ad_options', true );

    if ( empty( $ad_options ) ) {
        return;
    }

    $ad_options = maybe_unserialize( $ad_options );
    if ( is_array( $ad_options ) && isset( $ad_options['output']['image_id'] ) ) {
        $image_id = $ad_options['output']['image_id'];

        if ( get_post( $image_id ) ) {
            wp_delete_attachment( $image_id, true );
        }
    }
}Code language: PHP (php)

Please exercise caution when implementing this code, as it directly impacts the media library and the ads associated with the deleted images. Notably, if you utilize the same image banner file across multiple ads and delete one, including the image file, the related ads will stop working. Custom modifications like these can potentially affect other functionalities within Advanced Ads.

Make it better

Increase your ad management skills without spending more time.
Join over 150,000 publishers and AdOpts increasing their ad revenue.