Skip to content

get_product_variation_image_ids: fetch image ids directly from meta #60210

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: trunk
Choose a base branch
from

Conversation

mreishus
Copy link
Contributor

@mreishus mreishus commented Aug 5, 2025

Changes proposed in this Pull Request:

Refactor get_product_variation_image_ids() to directly query image IDs via get_post_meta instead of instantiating full WC_Product_Variation objects.

I was inspired after profiling showing this function being called multiple times per page (/product-category/clothing-grocery-garden/) and seeing a long loop/tail of function calls each time:
Screenshot 2025-08-05 at 3 49 01 PM

If we look at the bottom up view of this function, we can see a lot of time is spent in the chain of creating objects and data stores filling out information that isn't the image id:
Screenshot 2025-08-05 at 3 50 35 PM

Ultimately, the function is fetching one bit of meta:

class WC_Product_Variation extends WC_Product_Simple {
	public function get_image_id( $context = 'view' ) {
		$image_id = $this->get_prop( 'image_id', $context );

		if ( 'view' === $context && ! $image_id ) {
			$image_id = apply_filters( $this->get_hook_prefix() . 'image_id', $this->parent_data['image_id'], $this );
		}

		return $image_id;
	}
}

And the data class it inherits from calls a filter when we ->get_prop( 'image_id'

abstract class WC_Data {
	protected function get_prop( $prop, $context = 'view' ) {
		$value = null;

		if ( array_key_exists( $prop, $this->data ) ) {
			$value = array_key_exists( $prop, $this->changes ) ? $this->changes[ $prop ] : $this->data[ $prop ];

			if ( 'view' === $context ) {
				$value = apply_filters( $this->get_hook_prefix() . $prop, $value, $this );
			}
		}

		return $value;
	}
}

There are two complexities:

  • If there's not an image , it falls back to the parent's image
  • It runs the woocommerce_product_variation_get_image_id filter on the ids
    • Crucially, this passes a fully filled out object ($this) as the second parameter
    • This means if I bypass the work of filling out the object, then I am now violating the filter contract

Therefore, we can apply this optimization, but only if there's nothing on the filter. Note that since we're in a class that's designed as a helper for the product gallery block, we're always in "view" context.

How to test the changes in this Pull Request:

Goal 1: Seeing a gallery of variable products

  • Generate some global attributes and terms, then make some variable products that use these.
  • You may use wc-smooth-generator (https://github.com/woocommerce/wc-smooth-generator)
    • (option 1) use wp wc generate products 50 --type=variable
    • (option 2) use my branch, then wp wc generate attributes 36 --terms=200 and wp wc generate products 50 --type=variable --num-attributes=7 --max-terms=20 --max-variations=35 --use-existing-terms
  • You might have to make some extra variations on a product, so you can have a product with a lot of variations - maybe give some of the variations images
  • create a category and mass edit them to be in the category page
  • Visit the category page on the frontend, like /product-category/clothing-grocery-garden/

Goal 2: Observing the current results and timing on trunk

Use something like:

	public static function get_product_variation_image_ids( $product ) {
		$actual_link = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
		$t0 = microtime( true );

		$variation_image_ids = array();

		if ( ! $product instanceof \WC_Product ) {
			wc_doing_it_wrong( __FUNCTION__, __( 'Invalid product object.', 'woocommerce' ), '9.8.0' );
			return $variation_image_ids;
		}

		try {
			if ( $product->is_type( 'variable' ) ) {
				$variations = $product->get_children();
				foreach ( $variations as $variation_id ) {
					$variation = wc_get_product( $variation_id );
					if ( $variation ) {
						$variation_image_id = $variation->get_image_id();
						if ( ! empty( $variation_image_id ) && ! in_array( strval( $variation_image_id ), $variation_image_ids, true ) ) {
							$variation_image_ids[] = strval( $variation_image_id );
						}
					}
				}
			}
		} catch ( \Exception $e ) {
			// Log the error but continue execution.
			error_log( 'Error getting product variation image IDs: ' . $e->getMessage() );
		}

		$t1 = microtime( true );
		$execution_ms = ( $t1 - $t0 ) * 1000;
		error_log( "[$actual_link] get_product_variation_image_ids: {$execution_ms} ms | " . json_encode( $variation_image_ids ) );

		return $variation_image_ids;
	}

See some times over 10ms like:

[https://localhost:8081/product-category/clothing-grocery-garden/] get_product_variation_image_ids: 29.88 ms | ["147","154","146","149","134","161","137","157","153","148","138","158","151","145","141","156","160","143","159","152","162","150","155","140"]
[https://localhost:8081/product-category/clothing-grocery-garden/] get_product_variation_image_ids: 14.52 ms | ["148","153","156","154","157","151"]
[https://localhost:8081/product-category/clothing-grocery-garden/] get_product_variation_image_ids: 8.16 ms | ["95","159","103","77","152","79","138","123","121","145","133"]

Goal 2: Observing the propsed results and timing on this branch

Like above. Add:

		$actual_link = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
		$t0 = microtime( true );

To the top of the function and

		$t1 = microtime( true );
		$execution_ms = ( $t1 - $t0 ) * 1000;
		$execution_ms = round( $execution_ms, 2 );
		error_log( "[$actual_link] get_product_variation_image_ids: {$execution_ms} ms | " . json_encode( $variation_image_ids ) );

to the bottom. You should see the same results, but faster.

For me, for example:

[https://localhost:8081/product-category/clothing-grocery-garden/] get_product_variation_image_ids: 2.38 ms | ["147","154","146","149","134","161","137","157","153","148","138","158","151","145","141","156","160","143","159","152","162","150","155","140"]
[https://localhost:8081/product-category/clothing-grocery-garden/] get_product_variation_image_ids: 0.45 ms | ["148","153","156","154","157","151"]
[https://localhost:8081/product-category/clothing-grocery-garden/] get_product_variation_image_ids: 0.55 ms | ["95","159","103","77","152","79","138","123","121","145","133"]

Testing that has already taken place:

@mreishus mreishus self-assigned this Aug 5, 2025
@github-actions github-actions bot added the plugin: woocommerce Issues related to the WooCommerce Core plugin. label Aug 5, 2025
@mreishus mreishus marked this pull request as ready for review August 5, 2025 22:38
Copy link
Contributor

coderabbitai bot commented Aug 5, 2025

📝 Walkthrough

Walkthrough

A performance optimization was implemented in the WooCommerce plugin's get_product_variation_image_ids method. The function now retrieves variation image IDs directly from post metadata unless a specific filter is active, reducing unnecessary product object instantiations. A changelog entry documents this patch and its focus on performance improvement.

Changes

Cohort / File(s) Change Summary
Changelog Update
plugins/woocommerce/changelog/update-get-product-variation-image-ids
Added a changelog entry describing a patch update that improves performance by optimizing how variation image IDs are fetched in the WooCommerce plugin.
Product Gallery Utils Optimization
plugins/woocommerce/src/Blocks/Utils/ProductGalleryUtils.php
Refactored get_product_variation_image_ids to fetch image IDs directly from post meta when possible, avoiding product object creation unless a relevant filter is present; preserves filter extensibility and adds fallback logic.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~7 minutes

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 94cb3b7 and 8f6871a.

📒 Files selected for processing (2)
  • plugins/woocommerce/changelog/update-get-product-variation-image-ids (1 hunks)
  • plugins/woocommerce/src/Blocks/Utils/ProductGalleryUtils.php (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • plugins/woocommerce/changelog/update-get-product-variation-image-ids
  • plugins/woocommerce/src/Blocks/Utils/ProductGalleryUtils.php
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (21)
  • GitHub Check: Blocks e2e tests 9/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 10/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 7/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 2/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Metrics - @woocommerce/plugin-woocommerce [performance]
  • GitHub Check: Core e2e tests 3/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 5/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 1/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core API tests - @woocommerce/plugin-woocommerce [api]
  • GitHub Check: Core e2e tests 5/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 4/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Blocks e2e tests 3/10 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 6/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 2/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 4/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 1/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: PHP: 7.4 WP: latest - 1 [WP 6.7.3] 1/2 - @woocommerce/plugin-woocommerce [unit:php]
  • GitHub Check: PHP: 8.4 WP: latest [WP latest] 2/2 - @woocommerce/plugin-woocommerce [unit:php]
  • GitHub Check: PHP: 8.4 WP: latest [WP latest] 1/2 - @woocommerce/plugin-woocommerce [unit:php]
  • GitHub Check: Lint - @woocommerce/plugin-woocommerce
  • GitHub Check: build
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch reish20250805/update-get-product-variation-image-ids

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

github-actions bot commented Aug 5, 2025

Test using WordPress Playground

The changes in this pull request can be previewed and tested using a WordPress Playground instance.
WordPress Playground is an experimental project that creates a full WordPress instance entirely within the browser.

Test this pull request with WordPress Playground.

Note that this URL is valid for 30 days from when this comment was last updated. You can update it by closing/reopening the PR or pushing a new commit.

@mreishus mreishus force-pushed the reish20250805/update-get-product-variation-image-ids branch from 94cb3b7 to 8f6871a Compare August 7, 2025 18:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Performance plugin: woocommerce Issues related to the WooCommerce Core plugin.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant