WooCommerce升级至3.3.5后分类页商品名称无法显示求助(附代码)
Fix for Missing Category Name & Product Count on WooCommerce Category Pages After 3.3.5 Update
Hey there, I see exactly what's going wrong with your code—let's get your category name and product count showing again after the WooCommerce update!
What's Broken in Your Original Code
Your function has a few critical issues that are causing it to fail, especially with the newer WooCommerce version:
- You're using
get_term_by()incorrectly. The proper syntax isget_term_by( $field, $value, $taxonomy ), but you flipped the first two arguments and missed required parameters entirely. - You tried looping through
$terms, butget_term_by()returns a single term object (not an array) when used correctly—so that foreach loop was throwing errors under the hood. - Relying on
global $postand checkingis_tax()against the term name isn't reliable on category archive pages. WooCommerce 3.3+ adjusted how archive queries work, so using the queried object is a far more stable approach.
Fixed Code
Here's a revised version that works seamlessly with WooCommerce 3.3.5 and later:
function add_product_count_view() { // Grab the active product category from the current archive page query $current_category = get_queried_object(); // Only run this if we're on a valid product category archive if ( is_tax( 'product_cat' ) && is_a( $current_category, 'WP_Term' ) ) { // Output sanitized category name and built-in product count echo '<h3 class="woo-category-name">' . esc_html( $current_category->name ) . '<span class="woo-category-count">' . esc_html( $current_category->count ) . '</span></h3>'; } } // Hook the function to where you want it displayed (example hook below) // add_action( 'woocommerce_before_shop_loop', 'add_product_count_view' );
Why This Works Better
get_queried_object(): This directly pulls the active category from the page's query—no messy global variables or guesswork, which is critical for WooCommerce's updated archive system.- Validation Checks: The
is_tax()andis_a()checks prevent errors from firing on non-category pages. - Security:
esc_html()sanitizes the output to block potential XSS vulnerabilities (always a good practice for frontend output). - Built-in Count: WooCommerce automatically maintains the
countproperty for product categories, so you don't need extra database queries to get the product number.
Just make sure you hook the function to the right WooCommerce action (like woocommerce_before_shop_loop or woocommerce_archive_description) based on where you want the category name and count to appear on the page.
内容的提问来源于stack exchange,提问作者Artem Herasko
相关产品推荐
相关产品推荐

