Skip to content

Add cache priming to product grid blocks, product Button, and Product Gallery#63750

Merged
albarin merged 7 commits intotrunkfrom
add/cache-priming-blocks
Mar 19, 2026
Merged

Add cache priming to product grid blocks, product Button, and Product Gallery#63750
albarin merged 7 commits intotrunkfrom
add/cache-priming-blocks

Conversation

@albarin
Copy link
Copy Markdown
Contributor

@albarin albarin commented Mar 18, 2026

Submission Review Guidelines:

Changes proposed in this Pull Request:

Adds missing _prime_post_caches() calls in AbstractProductGrid.php, ProductGalleryUtils.php, and `ProductButton.php and reduces individual SQL queries.

Closes #63717
Closes https://linear.app/a8c/issue/WOOPLUG-6430/performance-blocks-missing-cache-priming-cases

Measured query reduction (Query Monitor):

Code path Before After Reduction
Legacy product grid (8 products with images) 107 queries 93 queries 14 fewer queries (13%)
Product Gallery block on variable product (3 variations) 128 queries 122 queries 6 fewer queries (5%)
Product Button for grouped product (3 children, custom template) 91 queries 88 queries 3 fewer queries (~1 per child)

Query savings scale linearly with the number of products/variations/children.

Not included: GroupedProductItem.php — Grouped product children are already cached by the time this block renders, so adding priming there would have no benefit.

How to test the changes in this Pull Request:

Prerequisites:

  • Install and activate Query Monitor
  • Test on trunk first (before), note the total query count from QM, then test on this branch (after)
  1. Legacy product grid blocks (AbstractProductGrid.php)

    • Ensure you have 8+ products with featured images set
    • Create a page with a legacy product grid block via WP-CLI:
      wp post create --post_type=page --post_status=publish --post_title="Test Product Grid" --post_content='<!-- wp:woocommerce/product-new {"columns":4,"rows":2} /-->'
      
    • Visit the page on the frontend
    • Check the total query count in Query Monitor
    • Expected: ~14 fewer queries with 8 products (measured: 107 → 93)
  2. Product Gallery block on variable product (ProductGalleryUtils.php)

    • Use a block theme (e.g., Twenty Twenty-Five)
    • Ensure the Single Product template includes the Product Gallery block (not individual Product Image blocks). If needed, edit the template in Appearance > Editor > Templates > Single Product and replace the image block with the Product Gallery block
    • Create or use an existing variable product with 3+ variations
    • Visit the variable product page on the frontend
    • Check the total query count in Query Monitor
    • Expected: ~6 fewer queries with 3 variations (measured: 128 → 122). Savings scale with the number of variations
  3. Product Button for grouped product (ProductButton.php)

    • Create a grouped product with 3+ child products
    • Set the child products' catalog visibility to hidden (so they are not loaded by the main shop query)
    • Edit the Product Catalog template (Appearance > Editor > Templates > Product Catalog)
    • In the Product Template block, remove the Product Image and Product Price blocks (these call is_on_sale() / get_price_html() which pre-cache grouped children)
    • Keep only Product Title and Add to Cart Button
    • Visit the Shop page on the frontend
    • Check the total query count in Query Monitor
    • Expected: ~1 fewer query per child product (measured: 91 → 88 with 3 children). Grouped products with more children will see proportionally greater savings

Milestone

Changelog entry

  • Automatically create a changelog entry from the details below.
Changelog Entry Details

Significance

  • Patch

Type

  • Performance - Address performance issues

Message

Reduce SQL queries on legacy product grid blocks, Product Gallery, and Product Button by adding missing "_prime_post_caches()" calls to batch-load post data.

@github-actions github-actions bot added the plugin: woocommerce Issues related to the WooCommerce Core plugin. label Mar 18, 2026
@albarin albarin changed the title Add cache priming to product grid blocks and Product Gallery Add cache priming to product grid blocks, product Button, and Product Gallery Mar 19, 2026
@albarin albarin marked this pull request as ready for review March 19, 2026 10:08
@woocommercebot woocommercebot requested review from a team and kraftbj and removed request for a team March 19, 2026 10:08
@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Mar 19, 2026

Testing Guidelines

Hi @kraftbj @kalessil ,

Apart from reviewing the code changes, please make sure to review the testing instructions (Guide) and verify that relevant tests (E2E, Unit, Integration, etc.) have been added or updated as needed.

Reminder: PR reviewers are required to document testing performed. This includes:

  • 🖼️ Screenshots or screen recordings.
  • 📝 List of functionality tested / steps followed.
  • 🌐 Site details (environment attributes such as hosting type, plugins, theme, store size, store age, and relevant settings).
  • 🔍 Any analysis performed, such as assessing potential impacts on environment attributes and other plugins, conducting performance profiling, or using LLM/AI-based analysis.

⚠️ Within the testing details you provide, please ensure that no sensitive information (such as API keys, passwords, user data, etc.) is included in this public issue.

@albarin albarin requested a review from kalessil March 19, 2026 10:09
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 19, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 09740046-e327-4af6-a002-fab5e189fc5d

📥 Commits

Reviewing files that changed from the base of the PR and between c91a45d and 60c756e.

📒 Files selected for processing (1)
  • plugins/woocommerce/src/Blocks/BlockTypes/AddToCartWithOptions/GroupedProductItem.php
✅ Files skipped from review due to trivial changes (1)
  • plugins/woocommerce/src/Blocks/BlockTypes/AddToCartWithOptions/GroupedProductItem.php

📝 Walkthrough

Walkthrough

Adds conditional calls to _prime_post_caches() in three block-related areas (AbstractProductGrid, ProductButton, ProductGalleryUtils) to batch-load post data before iterating product image attachments, grouped children, or variations; also adds a changelog entry and a non-functional comment in GroupedProductItem.

Changes

Cohort / File(s) Summary
Changelog Entry
plugins/woocommerce/changelog/63750-add-cache-priming-blocks
New changelog file documenting a patch performance update that reduces SQL query volume via cache priming.
Block Cache Priming
plugins/woocommerce/src/Blocks/BlockTypes/AbstractProductGrid.php, plugins/woocommerce/src/Blocks/BlockTypes/ProductButton.php, plugins/woocommerce/src/Blocks/Utils/ProductGalleryUtils.php
Adds conditional _prime_post_caches() calls before processing: primes image attachment IDs in AbstractProductGrid, primes grouped product child IDs in ProductButton, and primes variation IDs in ProductGalleryUtils. Calls are guarded by non-empty ID checks and casts where applicable.
Comment Only
plugins/woocommerce/src/Blocks/BlockTypes/AddToCartWithOptions/GroupedProductItem.php
Added an inline comment noting no cache priming is necessary because grouped children are already cached; no functional change.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and accurately summarizes the main change: adding cache priming to three product blocks (product grid blocks, Product Button, and Product Gallery), which aligns directly with the file changes.
Description check ✅ Passed The description is comprehensive and directly related to the changeset. It explains the changes, provides measured performance improvements with before/after query counts, and includes detailed testing instructions.
Linked Issues check ✅ Passed All primary objectives from issue #63717 are met: cache priming added to AbstractProductGrid.php [#63717], ProductGalleryUtils.php [#63717], ProductButton.php [#63717], and a clarifying comment added to GroupedProductItem.php [#63717] explaining why priming is not needed there.
Out of Scope Changes check ✅ Passed All changes are within scope: cache priming additions to three target files plus a clarifying comment in GroupedProductItem.php, plus a changelog entry. No unrelated or extraneous modifications are present.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch add/cache-priming-blocks
📝 Coding Plan
  • Generate coding plan for human review comments

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
plugins/woocommerce/src/Blocks/BlockTypes/ProductButton.php (1)

341-345: Normalize grouped child IDs before cache priming.

At Line 341, run get_children() through wp_parse_id_list() before calling _prime_post_caches() and iterating child products for stricter input handling.

Suggested refactor
-			$grouped_product_ids = $product->get_children();
+			$grouped_product_ids = wp_parse_id_list( $product->get_children() );
 			if ( ! empty( $grouped_product_ids ) ) {
 				_prime_post_caches( $grouped_product_ids );
 			}

As per coding guidelines: Guard all code against unexpected inputs and Sanitize and validate any potentially dangerous inputs.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@plugins/woocommerce/src/Blocks/BlockTypes/ProductButton.php` around lines 341
- 345, The grouped product children IDs returned by $product->get_children()
should be normalized before use: call wp_parse_id_list() on the result and
assign it back to $grouped_product_ids, then only call
_prime_post_caches($grouped_product_ids) and iterate the sanitized
$grouped_product_ids in the foreach; update references in the ProductButton
class/method where $grouped_product_ids, get_children(), _prime_post_caches(),
and the foreach loop are used to ensure inputs are validated.
plugins/woocommerce/src/Blocks/Utils/ProductGalleryUtils.php (1)

120-124: Normalize variation IDs before priming and iteration.

At Line 120, normalize get_children() with wp_parse_id_list() so unexpected extension-provided values don’t propagate into _prime_post_caches() and wc_get_product().

Suggested refactor
-				$variations = $product->get_children();
+				$variations = wp_parse_id_list( $product->get_children() );
 				if ( ! empty( $variations ) ) {
 					_prime_post_caches( $variations );
 				}

As per coding guidelines: Guard all code against unexpected inputs and Sanitize and validate any potentially dangerous inputs.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@plugins/woocommerce/src/Blocks/Utils/ProductGalleryUtils.php` around lines
120 - 124, Normalize and validate variation IDs returned by
$product->get_children() before using them: replace the direct call to
$product->get_children() with a sanitized list via wp_parse_id_list and ensure
$variations is an array (e.g., $variations = wp_parse_id_list(
$product->get_children() )); then use that $variations when calling
_prime_post_caches and in the foreach that calls wc_get_product() so unexpected
non-numeric or extension-provided values cannot propagate into
_prime_post_caches() or wc_get_product().
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@plugins/woocommerce/src/Blocks/BlockTypes/ProductButton.php`:
- Around line 341-345: The grouped product children IDs returned by
$product->get_children() should be normalized before use: call
wp_parse_id_list() on the result and assign it back to $grouped_product_ids,
then only call _prime_post_caches($grouped_product_ids) and iterate the
sanitized $grouped_product_ids in the foreach; update references in the
ProductButton class/method where $grouped_product_ids, get_children(),
_prime_post_caches(), and the foreach loop are used to ensure inputs are
validated.

In `@plugins/woocommerce/src/Blocks/Utils/ProductGalleryUtils.php`:
- Around line 120-124: Normalize and validate variation IDs returned by
$product->get_children() before using them: replace the direct call to
$product->get_children() with a sanitized list via wp_parse_id_list and ensure
$variations is an array (e.g., $variations = wp_parse_id_list(
$product->get_children() )); then use that $variations when calling
_prime_post_caches and in the foreach that calls wc_get_product() so unexpected
non-numeric or extension-provided values cannot propagate into
_prime_post_caches() or wc_get_product().

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 41377dd5-ed4f-4ae8-8153-948d945ae612

📥 Commits

Reviewing files that changed from the base of the PR and between a21c3c7 and c91a45d.

📒 Files selected for processing (4)
  • plugins/woocommerce/changelog/63750-add-cache-priming-blocks
  • plugins/woocommerce/src/Blocks/BlockTypes/AbstractProductGrid.php
  • plugins/woocommerce/src/Blocks/BlockTypes/ProductButton.php
  • plugins/woocommerce/src/Blocks/Utils/ProductGalleryUtils.php

@kalessil kalessil added this to the 10.7.0 milestone Mar 19, 2026
@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Mar 19, 2026

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.

@kalessil
Copy link
Copy Markdown
Contributor

Not included: GroupedProductItem.php — Grouped product children are already cached by the time this block renders, so adding priming there would have no benefit.

Can we add clarifying comments for those cases, so future people don't attempt to add caches there?

@albarin
Copy link
Copy Markdown
Contributor Author

albarin commented Mar 19, 2026

Can we add clarifying comments for those cases, so future people don't attempt to add caches there?

Good suggestions @kalessil, added a clarifying comment in GroupedProductItem.php

Copy link
Copy Markdown
Contributor

@kalessil kalessil left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me!

  • The code changes look good.
  • I followed the testing instructions and can confirm there is a reduction in the number of SQL queries.

@albarin albarin merged commit 5ba893c into trunk Mar 19, 2026
91 of 93 checks passed
@albarin albarin deleted the add/cache-priming-blocks branch March 19, 2026 11:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

plugin: woocommerce Issues related to the WooCommerce Core plugin.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Performance] Blocks: missing cache priming cases

3 participants