Custom_Image_Header::ajax_header_crop() WordPress Method

The Custom_Image_Header::ajax_header_crop() method is used to crop an image that has been uploaded as a header image. This is done using the WordPress Ajax API.

Custom_Image_Header::ajax_header_crop() #

Gets attachment uploaded by Media Manager, crops it, then saves it as a new object. Returns JSON-encoded object details.


Source

File: wp-admin/includes/class-custom-image-header.php

	public function ajax_header_crop() {
		check_ajax_referer( 'image_editor-' . $_POST['id'], 'nonce' );

		if ( ! current_user_can( 'edit_theme_options' ) ) {
			wp_send_json_error();
		}

		if ( ! current_theme_supports( 'custom-header', 'uploads' ) ) {
			wp_send_json_error();
		}

		$crop_details = $_POST['cropDetails'];

		$dimensions = $this->get_header_dimensions(
			array(
				'height' => $crop_details['height'],
				'width'  => $crop_details['width'],
			)
		);

		$attachment_id = absint( $_POST['id'] );

		$cropped = wp_crop_image(
			$attachment_id,
			(int) $crop_details['x1'],
			(int) $crop_details['y1'],
			(int) $crop_details['width'],
			(int) $crop_details['height'],
			(int) $dimensions['dst_width'],
			(int) $dimensions['dst_height']
		);

		if ( ! $cropped || is_wp_error( $cropped ) ) {
			wp_send_json_error( array( 'message' => __( 'Image could not be processed. Please go back and try again.' ) ) );
		}

		/** This filter is documented in wp-admin/includes/class-custom-image-header.php */
		$cropped = apply_filters( 'wp_create_file_in_uploads', $cropped, $attachment_id ); // For replication.

		$attachment = $this->create_attachment_object( $cropped, $attachment_id );

		$previous = $this->get_previous_crop( $attachment );

		if ( $previous ) {
			$attachment['ID'] = $previous;
		} else {
			unset( $attachment['ID'] );
		}

		$new_attachment_id = $this->insert_attachment( $attachment, $cropped );

		$attachment['attachment_id'] = $new_attachment_id;
		$attachment['url']           = wp_get_attachment_url( $new_attachment_id );

		$attachment['width']  = $dimensions['dst_width'];
		$attachment['height'] = $dimensions['dst_height'];

		wp_send_json_success( $attachment );
	}


Top ↑

Changelog

Changelog
VersionDescription
3.9.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.