You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为WooCommerce迷你购物车中的商品名称锚标签添加title属性?是否有对应实现函数?

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_name filter, 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 title attribute 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

  1. Add a product to your cart.
  2. Hover over the product name in your mini cart widget.
  3. You should see a tooltip displaying the full product name.

内容的提问来源于stack exchange,提问作者user15346394

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 13:08:12