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_idinteger (Required) Post ID.
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' ); 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 ); } } } }
Expand full source code Collapse full source code View on GitHub: includes/upload.php:471
Add your comment