Inventory_Presser_Admin_Photo_Arranger::remove_attachment_from_gallery( mixed $post_id, mixed $parent_id )

remove_attachment_from_gallery


Parameters Parameters

$post_id

(mixed) (Required)

$parent_id

(mixed) (Required)


Top ↑

Return Return

(void)


Top ↑

Source Source

File: includes/admin/class-admin-photo-arranger.php

	protected function remove_attachment_from_gallery( $post_id, $parent_id ) {
		$attachment = get_post( $post_id );

		// Is this attachment an image?
		if ( ! wp_attachment_is_image( $attachment ) ) {
			// No.
			return;
		}

		// Is this new attachment even attached to a post?
		$parent = get_post( $parent_id );

		// Is the new attachment attached to a vehicle?
		if ( empty( $parent->post_type ) || INVP::POST_TYPE !== $parent->post_type ) {
			// Parent post isn't a vehicle.
			return;
		}

		// Does the post content of the vehicle have a Gallery with a specific CSS class?
		$blocks = parse_blocks( $parent->post_content );
		foreach ( $blocks as $index => $block ) {
			// Is this a core gallery block? With a specific CSS class?
			if ( ! $this->is_gallery_block_with_specific_css_class( $block ) ) {
				continue;
			}

			// Does the block already have this attachment ID? Remove it.
			if ( ! empty( $block['innerBlocks'] )
				&& $this->inner_blocks_contains_id( $block, $post_id ) ) {

				$inner_block_count = count( $block['innerBlocks'] );
				for ( $b = 0; $b < $inner_block_count; $b++ ) {
					if ( $post_id === $block['innerBlocks'][ $b ]['attrs']['id'] ) {
						unset( $block['innerBlocks'][ $b ] );
						$block['innerBlocks'] = array_values( $block['innerBlocks'] );
						break;
					}
				}
			}

			// Change a CSS class to reflect the number of photos in the Gallery.
			$block['innerContent'][0] = preg_replace(
				'/ columns-[0-9]+/',
				' columns-' . count( $block['innerBlocks'] ) ?? 0,
				$block['innerContent'][0],
				2
			);

			// Remove a list item HTML that renders the image in the gallery.
			$pattern                  = sprintf(
				'/<!-- wp:image {"id":%1$d,"sizeSlug":"large","linkDestination":"none"} -->'
					. "[\r\n]*"
					. '<figure class="wp-block-image size-large"><img src="[^"]+" alt="" class="wp-image-%1$d"/></figure>'
					. "[\r\n]*"
					. '<!-- /wp:image -->/',
				$post_id
			);
			$block['innerContent'][0] = preg_replace(
				$pattern,
				'',
				$block['innerContent'][0]
			);

			// Update the block in the $blocks array.
			$blocks[ $index ] = $block;

			// and then update the post.
			$parent->post_content = serialize_blocks( $blocks );
			$this->safe_update_post( $parent );
			break;
		}
	}