贷款计算器显示 Woocommerce 内容产品循环中的每月付款金额

Loan Calculator to Show Monthly Payment Amount on Woocommerce Content Product Loop

我写了以下内容来计算产品页面上的每月付款。基本上贷款金额在5000以上或以下都需要加手续费,价格分别加99或49刀。

然后我计算出 36 个月内每月支付的费用为 12.99%,并将其输出到产品着陆页上。

我正在使用 get_post_meta(get_the_ID(), '_regular_price', true); 获取产品价格。

<?php

    function FinanceCalc() {

        function AddAdminFee() {

            $a = get_post_meta(get_the_ID(), '_regular_price', true);

            if ($a >= 5000) {
                return $a + 99;
            } else {
                return $a + 49;

            }

        }

        $loanamount = AddAdminFee();

        function calcPmt( $amt , $i, $term ) {

            $int = $i/1200;
            $int1 = 1+$int;
            $r1 = pow($int1, $term);

            $pmt = $amt*($int*$r1)/($r1-1);

            return $pmt;

        }

        $payment = calcPmt ( $loanamount, 12.99, 36 );

        return round($payment*100)/100;

    }

    $monthlypayment = FinanceCalc();

?>

然后我调用输出的价格如下。它仅限于特定类别,因为并非所有产品都需要此计算器。

<?php if ( has_term ( 'the-category-term-here', 'product_cat')) {
                                echo 'Finance this for $' . number_format($monthlypayment, 2) . ' per month';
                                }
                            ?>

我已将所有这些代码放在 content-single-product-default.php 上并且可以正常工作。当我尝试在 content-product.php 上执行此操作作为分类结果循环的一部分时,我收到以下错误:

Cannot redeclare FinanceCalc() (previously declared in .../content-product.php:100) in .../content-product.php on line 131

知道我哪里做错了吗?关于如何清理它以及是否有更好的方法的任何建议?

我只是通过简单的数学和 Google.

来摆弄 php 来写这篇文章

我很惊讶没有可用的插件。

您的函数代码需要位于您主题的 function.php 文件中(只需一次),但不能多次出现在不同的模板中。然后您将能够在不同的模板中多次调用(执行)而不会出现任何错误消息。请记住,一个函数只能声明一次。

现在你的主函数代码中真的不需要子函数,因为它们不会被多次调用......所以你的函数可以这样写:

function FinanceCalc() {

    $price = get_post_meta(get_the_ID(), '_regular_price', true);

    $loanamount = $price >= 5000 ? $price + 99 : $price + 49;

    $i = 12.99;
    $term = 36;
    $int = $i / 1200;
    $int1 = 1 + $int;
    $r1 = pow($int1, $term);

    $payment = $loanamount * $int * $r1 / ($r1 - 1);

    return round($payment * 100) / 100;
}

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。

现在在您的模板文件中,您可以调用它并以这种方式执行:

<?php if ( has_term ( 'the-category-term-here', 'product_cat')) {
    $monthlypayment = FinanceCalc();
    echo 'Finance this for $' . number_format($monthlypayment, 2) . ' per month';
} ?>

并且您可以调用 FinanceCalc() 函数并以类似的方式在您的其他模板文件中执行它...


更新:限制显示一定价格金额(与您的评论相关)

<?php if ( has_term ( 'the-category-term-here', 'product_cat')) {
    $price = get_post_meta(get_the_ID(), '_regular_price', true);
    if( $price >= 1000 ){
        $monthlypayment = FinanceCalc();
        echo 'Finance this for $' . number_format($monthlypayment, 2) . ' per month';
    }
} ?>