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 = array();

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

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

	// Make sure WP_Filesystem is loaded.
	if ( ! function_exists( 'WP_Filesystem' ) ) {
		require_once ABSPATH . 'wp-admin/includes/file.php';
	}

	// Initialize WP_Filesystem.
	if ( ! \WP_Filesystem() ) {
		// Unable to initialize WP_Filesystem, handle error accordingly.
		return;
	}

	global $wp_filesystem;

	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";
				$wp_filesystem->delete( $file );
			}
		}
	}
}

Leave a Reply

Your email address will not be published.

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

Add your comment