php 贷款计算器在Woocommerce内容产品循环上显示每月付款额

6tr1vspr  于 2024-01-05  发布在  PHP
关注(0)|答案(2)|浏览(120)

我写了下面的计算每月付款的产品页面。基本上它需要一个管理费被添加,如果贷款金额高于或低于5000,价格将分别增加99或49美元。
然后,我计算每月付款在12.99%超过36个月,并输出它在产品着陆页。
我用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 declare in./content-product.php:100)in./content-product.php on line 131
有什么线索我做错了吗?有什么建议也对如何清理这一点,如果有一个更好的方法?
我写这个只是用php,使用简单的数学和谷歌。
我很惊讶没有可用的插件。

ffx8fchx

ffx8fchx1#

你的函数代码需要在你的主题的function.php文件中(只声明一次),而不是在不同的模板中多次。这样你就可以在不同的模板中多次调用(执行)它而不会有任何错误消息。记住一个函数只能声明一次。
现在你并不需要在main函数代码中使用查尔兹函数,因为它们不会被多次调用.所以你的函数可以这样写:

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';
    }
} ?>

vm0i2vca

vm0i2vca2#

更新的PHP版本7.1+的更新是什么
你的PHP警告“遇到非数值值”行

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

字符串
&线

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

相关问题