php - Display a custom installment price below product price in WooCommerce

I am planing to show a new price on my WooCommerce product page for all products. This is the installment price per month. I need to show this below the normal price (variable price and simple price) something like this:

"Monthly payment" total=regular price/months (I want to have 3, 6, 8, 12, etc) I understand I would have to add it per line I have tried with this code but it is not showing up anything - I am starting with only 3 months. zero interest so it is really price/3

add_action( 'woocommerce_single_product_summary', 'show_emi', 20 );
function show_emi() {
   global $product; 

   $id = $product->get_id();

   $product = wc_get_product( $id );

   $a = $product->get_price();
   $b = 3;
   $total = $a/$b;
   
   echo $total;
}

Can someone please help me with the code (I am really not good with it) to display what I want with the text?

Answer

Solution:

Try the following example that will display a formatted installment price per month below the product price on single product pages for products and variations of variable products:

// Custom function that gets installment formatted price string *(the default divider value is 3)*
function get_installment_price_html( $active_price, $divider = 3 ) {
    return sprintf( __("installment: %s  per month", "woocommerce"), wc_price( get_installment_price( $active_price / $divider ) ) );
}

// Display installment formatted price on all product types except variable
add_action( 'woocommerce_single_product_summary', 'display_product_installment_price', 15 );
function display_product_installment_price() {
    global $product; 

    // Not for variable products
    if ( $product->is_type( 'variable' ) ) {
        // get active price for display
        $active_price = wc_get_price_to_display( $product );

        if ( $active_price ) {
            // Display formatted installment price below product price
            echo get_installment_price_html( $active_price );
        }
    }
}

// Display installment formatted price on product variations
add_filter( 'woocommerce_available_variation', 'display_variation_installment_price', 10, 3) ;
function display_variation_installment_price( $variation_data, $product, $variation ) {
    $active_price = $variation_data['display_price']; // Get active price for display

    if ( $active_price ) {
        // Display formatted installment price below product price
        $variation_data['price_html'] .= '<br>' . get_installment_price_html( $active_price );
    }
    return $variation_data;
}

Code goes in functions.php file of the active child theme (or active theme). It should works.

Note: You will need to make some changes to have different installment rates prices as you describe on your question??�

Source