add_filter to modify woocommerce_cart_item_name hyperlink

I would like to override the woocommerce_cart_item_name hyperlink in order to direct the user to my own page when they click on the name of the product in the cart. I do not want to modify the woocommerce cart.php or place a modified cart.php in my child theme WooCommerce directory. I have tried adding the following to my functions.php, but it does not work. My guess is that $_product->get_title() does not work within the scope of functions.php. What is the correct method that uses add_filter to override the woocommerce_cart_item_name? Thank you.

/* Function that returns custom product hyperlink */
function wc_cart_item_name_hyperlink() {
    return sprintf( '<a href="https://wordpress.stackexchange.com/questions/216353/%s">%s </a>','example.com/mypage/', $_product->get_title() );
}
/* Filter to override cart_item_name */
add_filter( 'woocommerce_cart_item_name', 'wc_cart_item_name_hyperlink' );

1 Answer
1

The key is to pass arguments to the callback function.

Try this:

/* Function that returns custom product hyperlink */
function wc_cart_item_name_hyperlink( $link_text, $product_data ) {
   $title = get_the_title($product_data['product_id']);
   return sprintf( '<a href="https://wordpress.stackexchange.com/questions/216353/%s">%s </a>','example.com/mypage/',$title );
}
/* Filter to override cart_item_name */
add_filter( 'woocommerce_cart_item_name', 'wc_cart_item_name_hyperlink', 10, 2 );

The $product_data parameter is an array that contains the product_id, variation_id, quantity, line_total, line_tax, line_subtotal, line_subtotal_tax, line_tax_data, as well as an inner array called variation that has more details.

Also, $product_data['data'] is the WC_Product_Simple object, which give you even more to work with.

Leave a Comment