如何为WooCommerce迷你购物车中的商品名称锚标签添加title属性?是否有对应实现函数?
How to Add Title Attribute to WooCommerce Mini Cart Product Links
Absolutely! You can easily add a title attribute to the product name anchor tags in your WooCommerce mini cart using a custom filter function. This will show the full product name as a tooltip when customers hover over the link.
Basic Solution (Applies to All Cart Instances)
Add this code to your theme's functions.php file, or a custom plugin for better maintainability:
add_filter( 'woocommerce_cart_item_name', 'add_title_to_mini_cart_product_links', 10, 3 ); function add_title_to_mini_cart_product_links( $name_html, $cart_item, $cart_item_key ) { // Get the product object from the cart item $product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key ); // Grab the sanitized product title to avoid XSS risks $product_title = esc_attr( $product->get_name() ); // Check if the output contains an anchor tag (standard in mini cart) if ( strpos( $name_html, '<a' ) !== false ) { // Insert the title attribute into the existing anchor tag $name_html = preg_replace( '/<a(.*?)>/', "<a$1 title=\"$product_title\">", $name_html ); } return $name_html; }
What This Does:
- Hooks into the
woocommerce_cart_item_namefilter, which controls how product names are rendered in all cart views (including the mini cart). - Retrieves the product object and sanitizes its title to keep your site secure.
- Uses a safe regex to inject the
titleattribute into the anchor tag, setting its value to the product's full name.
Optional: Restrict to Only the Mini Cart
If you want this change to only affect the mini cart (and not the main cart page or checkout flow), add a conditional check to target just the mini cart context:
add_filter( 'woocommerce_cart_item_name', 'add_title_to_mini_cart_only', 10, 3 ); function add_title_to_mini_cart_only( $name_html, $cart_item, $cart_item_key ) { // Only apply this to the mini cart (exclude main cart and WooCommerce endpoints) if ( ! is_cart() && ! is_wc_endpoint_url() ) { $product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key ); $product_title = esc_attr( $product->get_name() ); if ( strpos( $name_html, '<a' ) !== false ) { $name_html = preg_replace( '/<a(.*?)>/', "<a$1 title=\"$product_title\">", $name_html ); } } return $name_html; }
Testing the Function
- Add a product to your cart.
- Hover over the product name in your mini cart widget.
- You should see a tooltip displaying the full product name.
内容的提问来源于stack exchange,提问作者user15346394
相关产品推荐
相关产品推荐

