woocommerce_product_add_to_cart_url
Filters the URL of the add-to-cart button for products, allowing customization of the product add-to-cart link.
add_filter( 'woocommerce_product_add_to_cart_url', $callback, 10, 1 );
Description
Filters the URL generated for the "Add to Cart" button on product pages. Developers can modify this URL for custom add-to-cart behavior, such as redirecting to a specific page or handling variable products differently. The hook provides the current URL and the product object.
Usage
add_filter( 'woocommerce_product_add_to_cart_url', 'your_function_name', 10, 1 );
Return Value
The filtered value.
Examples
add_filter( 'woocommerce_product_add_to_cart_url', 'my_custom_add_to_cart_url', 10, 2 );
/**
* Customizes the 'Add to Cart' URL for specific products.
*
* This function demonstrates how to modify the default 'Add to Cart' URL.
* For example, it could be used to redirect users to a custom page or
* to a direct purchase link if the product has special attributes.
*
* @param string $url The current 'Add to Cart' URL.
* @param WC_Product $product The WC_Product object instance.
* @return string The modified 'Add to Cart' URL.
*/
function my_custom_add_to_cart_url( $url, $product ) {
// Example: If the product is a 'Subscription' type and has a specific meta key set,
// redirect to a custom subscription management page instead of the default add-to-cart.
if ( $product->is_type( 'subscription' ) && $product->get_meta( '_custom_subscription_link' ) ) {
$custom_link = $product->get_meta( '_custom_subscription_link' );
// Ensure it's a valid URL before returning
if ( filter_var( $custom_link, FILTER_VALIDATE_URL ) ) {
return esc_url( $custom_link );
}
}
// Example: For a product that is out of stock, change the button to "View Details"
// which links to the product's permalink.
if ( ! $product->is_in_stock() ) {
return get_permalink( $product->get_id() );
}
// Return the original URL if no custom logic is applied.
return $url;
}
Placement
This code should be placed in the functions.php file of your active theme, a custom plugin, or using a code snippets plugin.
Source Code
src/includes/woocommerce/wc_product_courses.php:50
src/includes/woocommerce/wc_product_group.php:51
src/includes/woocommerce/wc_product_license.php:51
public function add_to_cart_url() {
$url = add_query_arg( 'add-to-cart', $this->get_id(), wc_get_cart_url() );
return apply_filters( 'woocommerce_product_add_to_cart_url', $url, $this );
}