Tribe__Events__Community__Submission_Handler::insert_attachment( string $file_handler, int $post_id, bool $set_post_thumbnail = false )

Insert an attachment.


Parameters #

$file_handler

(string) (Required) The upload.

$post_id

(int) (Required) The post to attach the upload to.

$set_post_thumbnail

(bool) (Optional) To set or not to set the thumb.

Default value: false


Top ↑

Return #

(int) The attachment's ID.


Top ↑

Source #

File: src/Tribe/Submission_Handler.php

	public function insert_attachment( $file_handler, $post_id, $set_post_thumbnail = false ) {
		$events_label_singular = tribe_get_event_label_singular();

		// check to make sure its a successful upload
		if ( $_FILES[ $file_handler ]['error'] !== UPLOAD_ERR_OK ) {
			return false;
		}
		$uploaded_file_type = wp_check_filetype( basename( $_FILES[ $file_handler ]['name'] ) );
		$attach_id = false;

		if ( ! function_exists( 'media_handle_upload' ) ) {
			require_once( ABSPATH . 'wp-admin/includes/image.php' );
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
			require_once( ABSPATH . 'wp-admin/includes/media.php' );
		}

		$allowed_file_types = array( 'image/jpg', 'image/jpeg', 'image/gif', 'image/png' );
		if ( in_array( $uploaded_file_type['type'], $allowed_file_types ) ) {
			$attach_id = media_handle_upload( $file_handler, $post_id );
		} else {
			$this->add_message( esc_attr__( 'The file is not an Image', 'tribe-events-community' ), 'error' );
			return false;
		}

		if ( false !== $attach_id ) {
			$image_path = get_attached_file( $attach_id );
			$editor     = wp_get_image_editor( $image_path );
			$image      = @getimagesize( $image_path );
			$status     = true;

			if ( is_wp_error( $editor ) ) {
				$this->add_message( $editor->get_error_message(), 'error' );
				$status = false;
			} elseif ( false === $image ) {
				$this->add_message( esc_attr__( 'The file is not an Image', 'tribe-events-community' ), 'error' );
				$status = false;
			} elseif ( empty( $image[0] ) || ! is_numeric( $image[0] ) || empty( $image[1] ) || ! is_numeric( $image[1] ) ) {
				$this->add_message( esc_attr__( 'The image size is invalid', 'tribe-events-community' ), 'error' );
				$status = false;
			} elseif ( empty( $image[2] ) || ! in_array( $image[2], array( IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG ) ) ) {
				$this->add_message( esc_attr__( 'The file is not a valid image', 'tribe-events-community' ), 'error' );
				$status = false;
			}

			if ( false === $status ) {
				// Purge this weird file!
				wp_delete_attachment( $attach_id, true );
				return false;
			}

			if ( true === $set_post_thumbnail ) {
				update_post_meta( $post_id, '_thumbnail_id', $attach_id );
			}
		}

		return $attach_id;
	}

Top ↑

Changelog #

Changelog
Version Description
4.0.4 Introduced.