wc_apply_product_image_overrides()WC 10.8.0

Hook get_image_id / get_gallery_image_ids on a single product instance and return a callable that removes the hooks. Each filter only fires for the specified product ID — other product objects in the same render pass are unaffected.

No Hooks.

Returns

callable. Invocation of the returned callable removes both filters.

Usage

wc_apply_product_image_overrides( $product, $featured_id, $gallery_ids ): callable;
$product(WC_Product) (required)
Product to scope the override to.
$featured_id(int) (required)
Image ID to return from get_image_id.
$gallery_ids(int[]) (required)
Image IDs to return from get_gallery_image_ids.

Changelog

Since 10.8.0 Introduced.

wc_apply_product_image_overrides() code WC 10.9.1

function wc_apply_product_image_overrides( WC_Product $product, int $featured_id, array $gallery_ids ): callable {
	$product_id = $product->get_id();

	$featured_filter = static function ( $value, $instance ) use ( $product_id, $featured_id ) {
		return ( $instance instanceof WC_Product && $instance->get_id() === $product_id )
			? $featured_id
			: $value;
	};

	$gallery_filter = static function ( $value, $instance ) use ( $product_id, $gallery_ids ) {
		return ( $instance instanceof WC_Product && $instance->get_id() === $product_id )
			? $gallery_ids
			: $value;
	};

	add_filter( 'woocommerce_product_get_image_id', $featured_filter, 10, 2 );
	add_filter( 'woocommerce_product_get_gallery_image_ids', $gallery_filter, 10, 2 );

	return static function () use ( $featured_filter, $gallery_filter ) {
		remove_filter( 'woocommerce_product_get_image_id', $featured_filter, 10 );
		remove_filter( 'woocommerce_product_get_gallery_image_ids', $gallery_filter, 10 );
	};
}