ap_delete_images_not_in_content( integer $post_id )

Description #

Delete images uploaded in post.

This function should be called after saving post content. This will find previously uploaded images from post meta and then compare with the image src present in content and if any image does not exists then image file and post meta is deleted.

Parameters #

  • $post_id
    integer (Required) Post ID.

Changelog #

VersionDescription
4.1.8Introduced.

Source #

File: includes/upload.php

function ap_delete_images_not_in_content( $post_id ) {
	$_post  = ap_get_post( $post_id );

	preg_match_all( '/<img.*?src\s*="([^"]+)".*?>/', $_post->post_content, $matches, PREG_SET_ORDER );

	$new_matches = [];

	if ( ! empty( $matches ) ) {
		foreach ( $matches as $m ) {
			$new_matches[] = basename( $m[1] );
		}
	}

	$images  = get_post_meta( $post_id, 'anspress-image' );

	if ( ! empty( $images ) ) {
		// Delete image if not in $matches.
		foreach ( $images as $img ) {
			if ( ! in_array( $img, $new_matches, true ) ) {
				delete_post_meta( $post_id, 'anspress-image', $img );

				$uploads = wp_upload_dir();
				$file    = $uploads['basedir'] . "/anspress-uploads/$img";
				unlink( $file );
			}
		}
	}
}

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Add your comment