php 根据类别或标签为每个产品添加多项费用

z0qdvdin  于 5个月前  发布在  PHP
关注(0)|答案(1)|浏览(51)

我目前正试图添加2自定义产品费用对我的woocommerce商店的基础上的产品类别。
自定义费用1 $3,60对于类别39中的所有产品
自定义费用2 $1,80对于类别38中的所有产品
这是我目前使用的代码:

function df_add_ticket_surcharge( $cart_object ) {

    global $woocommerce;
    $specialfeecat = 39;
    $spfee = 0.00;
    $spfeeperprod = 3.60;

    foreach ( $cart_object->cart_contents as $key => $value ) {

        $proid = $value['product_id'];
        $quantiy = $value['quantity'];
        $itmprice = $value['data']->price;

        $terms = get_the_terms( $proid, 'product_cat' );
        if ( $terms && ! is_wp_error( $terms ) ) :
            foreach ( $terms as $term ) {
                $catid = $term->term_id;
                if($specialfeecat == $catid ) {
                    $spfee = $quantiy * $spfeeperprod;
                }
            }
        endif;
    }

    if($spfee > 0 ) {

        $woocommerce->cart->add_fee( 'Statiegeld', $spfee, true, 'standard' );
    }

}

add_action( 'woocommerce_cart_calculate_fees', 'df_add_ticket_surcharge' );

字符串
这与预期的一样,产品类别中的所有产品:39在结账时获得自定义费用。
我遇到的问题是让这个与另一个产品类别和价值工作。当我尝试复制相同的代码两次,它返回一个关键的wordpress错误。
我想做的是
自定义费用1 $3,60对于类别39中的所有产品
自定义费用2 $1,80对于类别38中的所有产品
如果有人能把我带到正确的方向,我将不胜感激!

cgh8pdjw

cgh8pdjw1#

您可以使用switch语句根据类别id有条件地设置每个类别的价格。如下所示:

function df_add_ticket_surcharge( $cart_object ) {

    global $woocommerce;

    $spfee = 0.00; // Move the initialization outside of the loop

    foreach ( $cart_object->cart_contents as $key => $value ) {

        $proid = $value['product_id'];
        $quantiy = $value['quantity'];

        $terms = get_the_terms( $proid, 'product_cat' );

        $spcustomfee = 0.00;

        if ( $terms && ! is_wp_error( $terms ) ) {
            foreach ( $terms as $term ) {
                $catid = $term->term_id; // Get the id
                // Set each id to the fee you want to charge/
                switch ( $catid ) {
                    case 39:
                        $spcustomfee = 3.60;
                        break;
                    case 38:
                        $spcustomfee = 1.80;
                        break;
                    // Add more cases for other categories if needed
                }
            }

            $spfee += $quantiy * $spcustomfee;
        }
    }

    if ( $spfee > 0 ) {
        $woocommerce->cart->add_fee( 'Custom Fee', $spfee, true, 'standard' );
    }
}

add_action( 'woocommerce_cart_calculate_fees', 'df_add_ticket_surcharge' );

字符串

相关问题