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