Form_Upload_Manager::delete_old_files( awsmug\Torro_Forms\DB_Objects\Submissions\Submission $submission, awsmug\Torro_Forms\DB_Objects\Forms\Form $form, int $element_id, string $field = '_main', int $ignore_id )

Deletes old files for a specific form submission and element.

Description

This should be used when a user uploads a new file for a field, to prevent database clutter from the now unneeded files previously uploaded.

See also

Parameters

$submission

(awsmug\Torro_Forms\DB_Objects\Submissions\Submission) (Required) Submission object.

$form

(awsmug\Torro_Forms\DB_Objects\Forms\Form) (Required) Form object.

$element_id

(int) (Required) Element ID.

$field

(string) (Optional) Element field slug. Default is '_main'.

Default value: '_main'

$ignore_id

(int) (Optional) New attachment ID, so that it is not deleted. Default none.

Return

(array) Array where each element is either the deleted attachment ID, or an error object indicating a deletion failure. May also be empty in case nothing needed to be deleted.

Source

File: src/components/form-upload-manager.php

	public function delete_old_files( $submission, $form, $element_id, $field = '_main', $ignore_id = 0 ) {
		$prefix = $this->get_prefix();

		if ( ! $field ) {
			$field = '_main';
		}

		$args = array(
			'fields'         => 'ids',
			'posts_per_page' => 20,
			'no_found_rows'  => true,
			'post_type'      => 'attachment',
			'post_status'    => 'inherit',
			'meta_query'     => array(
				'relation' => 'AND',
				array(
					'key'   => $prefix . 'parent_submission_id',
					'value' => $submission->id,
					'type'  => 'UNSIGNED',
				),
				array(
					'key'   => $prefix . 'parent_element_id',
					'value' => $element->id,
					'type'  => 'UNSIGNED',
				),
				array(
					'key'   => $prefix . 'parent_element_field',
					'value' => $field,
					'type'  => 'CHAR',
				),
			),
		);

		if ( ! empty( $ignore_id ) ) {
			$args['post__not_in'] = array( $ignore_id );
		}

		$attachment_ids = get_posts( $args );

		$result = array();
		foreach ( $attachment_ids as $attachment_id ) {
			$post = wp_delete_attachment( $attachment_id, true );
			if ( ! $post ) {
				$result[] = new WP_Error( 'delete_error', __( 'The file could not be deleted.', 'torro-forms' ) );
			} else {
				$result[] = $post->ID;
			}
		}

		return $result;
	}

Changelog

Changelog
Version Description
1.0.0 Introduced.