AnsPress_Uploader::cron_delete_temp_attachments()

Description #

Delete temporary media which are older then today.

Changelog #

VersionDescription
4.1.8Introduced.

Source #

File: includes/upload.php

	public static function cron_delete_temp_attachments() {
		global $wpdb;

		$posts = $wpdb->get_results( "SELECT ID, post_author, post_parent FROM $wpdb->posts WHERE post_type = 'attachment' AND post_title='_ap_temp_media' AND post_date <= CURDATE()" ); // phpcs:ignore WordPress.DB

		$authors = array();

		if ( $posts ) {
			foreach ( (array) $posts as $_post ) {
				wp_delete_attachment( $_post->ID, true );
				ap_update_post_attach_ids( $_post->post_parent );
				$authors[] = $_post->post_author;
			}

			// Update temporary attachment counts of a user.
			foreach ( (array) array_unique( $authors ) as $author ) {
				ap_update_user_temp_media_count( $author );
			}
		}

		// Delete all temporary files.
		$uploads  = wp_upload_dir();
		$files    = glob( $uploads['basedir'] . '/anspress-temp/*' );
		$interval = strtotime( '-2 hours' );

		// 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 ( $files ) {
			foreach ( $files as $file ) {
				if ( filemtime( $file ) <= $interval ) {
					$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