How to add price to the "Subscribe" button using the WooCommerce Subscriptions in WooCommerce?

Viewed 81

How do I add the price of a subscription to the Subscribe button?

Instead of only show "Subscribe" I would like to state "Subscribe - $140" or "Subscribe every 2nd month for $140"

I have this code that works perfect with all simple products, but not subscriptions...

/**
 * @snippet       Add Price to "Add to Cart" Button
 * @author        LoicTheAztec
 * @compatible    WooCommerce 5.8
 * @source        https://stackoverflow.com/a/51584094/4275509
 */


add_filter('woocommerce_product_add_to_cart_text', 'custom_add_to_cart_price', 20, 2); // Shop and other archives pages
add_filter('woocommerce_product_single_add_to_cart_text', 'custom_add_to_cart_price', 20, 2); // Single product pages
function custom_add_to_cart_price($button_text, $product)
{
    // Variable products
    if ($product->is_type('variable')) {
        // shop and archives
        if (!is_product()) {
            $product_price = wc_price(wc_get_price_to_display($product, array('price' => $product->get_variation_price())));
            return $button_text . ' - From ' . strip_tags($product_price);
        }
        // Single product pages
        else {
            return $button_text;
        }
    }
    // All other product types
    else {
        $product_price = wc_price(wc_get_price_to_display($product));
        return $button_text . ' – ' . strip_tags($product_price);
    }
}
```
1 Answers

You can get product type using get_the_terms() function. try below code. code will go in your active theme functions.php file.

add_filter('woocommerce_product_add_to_cart_text', 'custom_add_to_cart_price', 20, 2); // Shop and other archives pages
add_filter('woocommerce_product_single_add_to_cart_text', 'custom_add_to_cart_price', 20, 2); // Single product pages
function custom_add_to_cart_price($button_text, $product){
    $product_type = get_the_terms( $product->get_id(),'product_type' )[0]->slug;
    // Variable products
    if ( $product_type == 'subscription' ) {
        $product_price = wc_price(wc_get_price_to_display($product));
        return $button_text . ' – ' . strip_tags($product_price);
    } else {
        return $button_text;       
    }
}
Related