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

问题描述 投票:1回答:1

我写了以下内容来计算产品页面上的每月付款。基本上,如果贷款金额高于或低于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上执行此操作作为分类结果循环的一部分时,我收到以下错误:

不能在第131行的... / content-product.php中重新声明FinanceCalc()(之前在... / content-product.php:100中声明)

我有什么问题吗?关于如何清理它以及是否有更好的方法的任何建议?

我只是通过使用简单的数学和谷歌来解决这个问题。

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

php wordpress woocommerce product price
1个回答
1
投票

您的功能代码需要在主题的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';
    }
} ?>
© www.soinside.com 2019 - 2024. All rights reserved.