Skip to content

Product Filters: Add get_taxonomy_counts method to FilterData class #59462

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

Conversation

dinhtungdu
Copy link
Member

@dinhtungdu dinhtungdu commented Jul 7, 2025

Submission Review Guidelines:

Changes proposed in this Pull Request:

Add get_taxonomy_counts method to FilterData class for calculating taxonomy term counts in product filters.

Closes #59129 (WOOPLUG-4765)

Screenshots or screen recordings:

This PR does not include UI changes.

How to test the changes in this Pull Request:

Applied the following snippet and go to Shop/Category/filtered Shop page. Manual verify that the count matches current results.

add_action(
    'wp_body_open', function () {
        global $wp_query;
        $container        = wc_get_container();
        $taxonomy_counts  = $container
            ->get(Automattic\WooCommerce\Internal\ProductFilters\FilterDataProvider::class)
            ->with($container->get(Automattic\WooCommerce\Internal\ProductFilters\QueryClauses::class))
            ->get_taxonomy_counts(array_filter($wp_query->query_vars), 'product_cat');
        echo '<pre>';
        echo '<table>';
        foreach ($taxonomy_counts as $taxonomy_id => $count) {
            $category = get_term($taxonomy_id, 'product_cat');
            if ($category) {
                echo '<tr>';
                echo '<td>' . $category->name . '</td>';
                echo '<td>' . $count . '</td>';
                echo '</tr>';
            }
        }
        echo '</table>';
        echo '</pre>';
    }
);

Adds the  method to the  class to calculate product counts for a given
taxonomy. This is used by the product filter blocks to show the number
of products for each filter option.
@github-actions github-actions bot added the plugin: woocommerce Issues related to the WooCommerce Core plugin. label Jul 7, 2025
@woocommercebot woocommercebot requested review from a team and Aljullu and removed request for a team July 7, 2025 05:16
Copy link
Contributor

github-actions bot commented Jul 7, 2025

Testing Guidelines

Hi @Aljullu ,

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.

@dinhtungdu dinhtungdu force-pushed the wooplug-4765-add-filterdataget_taxonomy_counts-method-to-calculate-the branch from 47f2675 to 00d2de2 Compare July 7, 2025 05:19
Copy link
Contributor

coderabbitai bot commented Jul 7, 2025

📝 Walkthrough

Walkthrough

A new get_taxonomy_counts method was introduced to the FilterData class in the WooCommerce Product Filters system. This method calculates taxonomy term counts for products matching given query variables. Related tests and setup/teardown routines were added and extended to ensure proper coverage and cleanup of product taxonomy data.

Changes

File(s) Change Summary
plugins/woocommerce/src/Internal/ProductFilters/FilterData.php Added public get_taxonomy_counts method for calculating taxonomy term counts with caching and hooks; updated get_attribute_counts for consistency.
plugins/woocommerce/tests/php/src/Internal/ProductFilters/FilterDataTest.php Added tests for get_taxonomy_counts with/without price filtering; added helper for expected counts.
plugins/woocommerce/tests/php/src/Internal/ProductFilters/AbstractProductFiltersTest.php Enhanced setup/teardown for product categories; added property and cleanup method for categories.
plugins/woocommerce/changelog/wooplug-4765-add-filterdataget_taxonomy_counts-method-to-calculate-the Changelog entry for new get_taxonomy_counts method.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant FilterData
    participant WordPress
    participant Database
    Client->>FilterData: get_taxonomy_counts(query_vars, taxonomy)
    FilterData->>WordPress: Apply 'woocommerce_pre_product_filter_data' filter
    alt Pre-filter returns array
        FilterData-->>Client: Return pre-filtered counts
    else No pre-filter result
        FilterData->>WordPress: Check transient cache
        alt Cache hit
            FilterData-->>Client: Return cached counts
        else Cache miss
            FilterData->>WordPress: Get matching product IDs (WP_Query)
            FilterData->>Database: SQL query for term counts (term_relationships, term_taxonomy)
            Database-->>FilterData: Raw term counts
            FilterData->>WordPress: Apply 'woocommerce_product_filter_data' filter
            FilterData->>WordPress: Set transient cache
            FilterData-->>Client: Return calculated counts
        end
    end
Loading

📜 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 b5605e4 and 3e5d613.

📒 Files selected for processing (3)
  • plugins/woocommerce/src/Internal/ProductFilters/FilterData.php (1 hunks)
  • plugins/woocommerce/tests/php/src/Internal/ProductFilters/AbstractProductFiltersTest.php (5 hunks)
  • plugins/woocommerce/tests/php/src/Internal/ProductFilters/FilterDataTest.php (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • plugins/woocommerce/tests/php/src/Internal/ProductFilters/AbstractProductFiltersTest.php
  • plugins/woocommerce/tests/php/src/Internal/ProductFilters/FilterDataTest.php
  • plugins/woocommerce/src/Internal/ProductFilters/FilterData.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). (1)
  • GitHub Check: build
✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • @coderabbitai modularize this function.
  • 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.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

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 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

@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.

Actionable comments posted: 0

🧹 Nitpick comments (1)
plugins/woocommerce/changelog/wooplug-4765-add-filterdataget_taxonomy_counts-method-to-calculate-the (1)

4-5: Complete the changelog description.

The changelog description appears to be incomplete. Line 4 ends with "for efficient" and line 5 is empty, suggesting the description was cut off mid-sentence.

Complete the description to properly explain what the method does:

-Product Filters: add `get_taxonomy_counts` method to FilterData class for efficient
+Product Filters: add `get_taxonomy_counts` method to FilterData class for efficient calculation of taxonomy term counts
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f6b7616 and 47f2675.

📒 Files selected for processing (4)
  • plugins/woocommerce/changelog/wooplug-4765-add-filterdataget_taxonomy_counts-method-to-calculate-the (1 hunks)
  • plugins/woocommerce/src/Internal/ProductFilters/FilterData.php (1 hunks)
  • plugins/woocommerce/tests/php/src/Internal/ProductFilters/AbstractProductFiltersTest.php (5 hunks)
  • plugins/woocommerce/tests/php/src/Internal/ProductFilters/FilterDataTest.php (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`plugins/woocommerce/tests/**/*.php`: Run WooCommerce PHPUnit tests for specific...

plugins/woocommerce/tests/**/*.php: Run WooCommerce PHPUnit tests for specific files or directories using the command: pnpm run test:php:env {relative_path} --verbose, and ensure the command is run in the plugins/woocommerce directory.

📄 Source: CodeRabbit Inference Engine (.cursor/rules/woo-phpunit.mdc)

List of files the instruction was applied to:

  • plugins/woocommerce/tests/php/src/Internal/ProductFilters/AbstractProductFiltersTest.php
  • plugins/woocommerce/tests/php/src/Internal/ProductFilters/FilterDataTest.php
🧠 Learnings (1)
plugins/woocommerce/tests/php/src/Internal/ProductFilters/AbstractProductFiltersTest.php (2)
Learnt from: gigitux
PR: woocommerce/woocommerce#58846
File: plugins/woocommerce/client/blocks/tests/e2e/tests/all-products/all-products.block_theme.spec.ts:41-52
Timestamp: 2025-06-16T09:20:22.981Z
Learning: In WooCommerce E2E tests, the database is reset to the initial state for each test, so there's no need to manually restore global template changes (like clearing the header template) as the test infrastructure handles cleanup automatically.
Learnt from: mreishus
PR: woocommerce/woocommerce#58817
File: plugins/woocommerce/includes/wc-product-functions.php:140-140
Timestamp: 2025-06-13T23:52:46.221Z
Learning: In WooCommerce's wc_delete_product_transients function, the context check includes both $is_admin_page (for regular admin screens) and $is_privileged_ajax (for AJAX requests from users with edit_products capability), ensuring that legitimate admin AJAX operations like product imports/exports can still delete transients.
🧬 Code Graph Analysis (3)
plugins/woocommerce/tests/php/src/Internal/ProductFilters/AbstractProductFiltersTest.php (1)
plugins/woocommerce/src/Enums/ProductStockStatus.php (1)
  • ProductStockStatus (10-38)
plugins/woocommerce/src/Internal/ProductFilters/FilterData.php (1)
plugins/woocommerce/includes/wc-formatting-functions.php (1)
  • wc_sanitize_taxonomy_name (64-66)
plugins/woocommerce/tests/php/src/Internal/ProductFilters/FilterDataTest.php (1)
plugins/woocommerce/src/Internal/ProductFilters/FilterData.php (1)
  • get_taxonomy_counts (297-349)
⏰ 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). (14)
  • GitHub Check: Metrics - @woocommerce/plugin-woocommerce [performance]
  • GitHub Check: Core API tests - @woocommerce/plugin-woocommerce [api]
  • GitHub Check: PHP: 8.4 WP: latest [WP latest] 2/2 - @woocommerce/plugin-woocommerce [unit:php]
  • GitHub Check: Core e2e tests 5/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 6/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 3/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 4/6 - @woocommerce/plugin-woocommerce [e2e]
  • GitHub Check: Core e2e tests 2/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.2] 1/2 - @woocommerce/plugin-woocommerce [unit:php]
  • GitHub Check: PHP: 7.4 WP: latest - 1 [WP 6.7.2] 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
🔇 Additional comments (15)
plugins/woocommerce/tests/php/src/Internal/ProductFilters/AbstractProductFiltersTest.php (5)

36-41: LGTM: Property addition follows established patterns.

The new $product_categories property is properly documented and follows the same pattern as other test properties in the class.


90-94: LGTM: Category setup is well-structured.

The category creation uses the existing FixtureData helper and stores the results in a logical key-value structure for easy reference in product assignments.


101-101: LGTM: Product category assignments are consistent.

The category assignments properly use the term IDs from the created categories and follow logical groupings:

  • Products 1, 4, 5, 6 assigned to cat-1
  • Products 2, 3 assigned to cat-2
  • Product 3 also assigned to cat-3 (testing multi-category assignment)

Also applies to: 107-107, 113-116, 122-122, 127-127, 152-152


190-190: LGTM: Cleanup integration follows established pattern.

The addition of category cleanup in tearDown() follows the same pattern as existing cleanup calls.


260-267: LGTM: Cleanup method is properly implemented.

The remove_all_product_categories() method follows the established pattern of other cleanup methods in the class. It properly iterates through the created categories and deletes them from the correct taxonomy.

plugins/woocommerce/src/Internal/ProductFilters/FilterData.php (6)

290-296: LGTM: Method signature and documentation are consistent.

The method signature, parameter types, and return type documentation follow the same pattern as get_attribute_counts(). The parameter naming is clear and follows conventions.


297-305: LGTM: Pre-filter hook implementation is consistent.

The pre-filter hook implementation follows the exact same pattern as other count methods, using the appropriate filter type 'taxonomy' and passing the taxonomy name in the extra parameters.


307-312: LGTM: Caching implementation follows established pattern.

The transient key generation and cache retrieval logic is identical to other count methods, ensuring consistent caching behavior across the class.


320-328: LGTM: SQL query is well-constructed and secure.

The SQL query properly:

  • Uses esc_sql() and wc_sanitize_taxonomy_name() for security
  • Joins the correct tables (term_relationships and term_taxonomy)
  • Counts distinct object_id (products) per term_taxonomy_id
  • Groups by term_taxonomy_id as expected

The query structure is appropriate for counting taxonomy term usage.


336-338: LGTM: Result processing follows established pattern.

The result processing using wp_list_pluck() and array_map('absint', ...) is identical to the get_attribute_counts() method, ensuring consistent data formatting.


341-348: LGTM: Post-filter hook and caching are consistent.

The post-filter hook and cache storage follow the exact same pattern as other count methods, ensuring consistent behavior and proper result filtering/caching.

plugins/woocommerce/tests/php/src/Internal/ProductFilters/FilterDataTest.php (4)

269-279: LGTM: Default query test follows established pattern.

The test method follows the same structure as test_get_attribute_counts_with_default_query(), properly testing the basic functionality of the new method with appropriate assertions.


281-301: LGTM: Filtered query test provides good coverage.

The test with max_price filter follows the same pattern as the attribute count tests, using a filter callback to determine which products should be included. This ensures the new method works correctly with query filters.


344-375: LGTM: Helper method correctly calculates expected counts.

The get_expected_category_counts() helper method:

  • Follows the same pattern as get_expected_attribute_counts()
  • Properly handles the optional filter callback
  • Correctly iterates through product data and category assignments
  • Returns the expected format (term_id => count mapping)

This ensures test assertions have accurate expected values to compare against.


269-301: Verify PHPUnit tests for new taxonomy-count functionality

Please confirm that the two new tests in FilterDataTest pass locally before merging:

• test_get_taxonomy_counts_with_default_query
• test_get_taxonomy_counts_with_max_price

Ensure all plugin dependencies are installed, then run one of the following from the repository root:

– Using pnpm/wp-env

cd plugins/woocommerce
pnpm install
pnpm run test:php:env tests/php/src/Internal/ProductFilters/FilterDataTest.php --verbose

If you get “wp-env: not found,” install or link @wordpress/env (e.g. npm install -g @wordpress/env).

– Using Composer/Phar PHPUnit

cd plugins/woocommerce
composer install
vendor/bin/phpunit -c phpunit.xml --verbose tests/php/src/Internal/ProductFilters/FilterDataTest.php

Confirm both tests pass without errors.

Copy link
Contributor

github-actions bot commented Jul 7, 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.

Copy link
Contributor

@Aljullu Aljullu left a comment

Choose a reason for hiding this comment

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

The code looks good, and the counts seem to be good as well:

imatge

There are a few linting errors and warnings, but besides that, LGTM.

Testing environment
  • WordPress 6.8.1 local dev environment
  • Plugins: WooCommerce Beta Tester
  • Theme: Woo Starter Theme
  • Store creation: June 2025
  • Store size: small

@dinhtungdu dinhtungdu force-pushed the wooplug-4765-add-filterdataget_taxonomy_counts-method-to-calculate-the branch from b5605e4 to 3e5d613 Compare July 7, 2025 13:17
@dinhtungdu dinhtungdu merged commit 3a41b82 into trunk Jul 8, 2025
47 of 49 checks passed
@dinhtungdu dinhtungdu deleted the wooplug-4765-add-filterdataget_taxonomy_counts-method-to-calculate-the branch July 8, 2025 04:30
@github-actions github-actions bot added this to the 10.1.0 milestone Jul 8, 2025
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.

Add FilterData::get_taxonomy_counts method to calculate the counts for taxonomy term
2 participants