为了账号安全,请及时绑定邮箱和手机立即绑定

是否有可能制定自定义价格?

是否有可能制定自定义价格?

PHP
忽然笑 2021-10-22 14:40:01
我在 Wordpress 上通过 WooCommerce 销售礼品卡。我的客户应该能够自己设置礼品卡金额的值。我只能通过插件来做到这一点。是否有可能通过更改一些代码或通过functions.php 来做到这一点?已安装 Pimwick 礼品卡 Pro
查看完整描述

1 回答

?
饮歌长啸

TA贡献1951条经验 获得超3个赞

是的,但如果从没有额外插件的全新 WooCommerce 安装中执行此操作,这是一个相当复杂的过程。你需要做以下事情来实现它:

  1. 为产品添加自定义输入字段以添加自定义价格

  2. 将该产品添加到购物车时,将自定义输入字段中的数据保存到会话(购物车)

  3. 创建订单时,将购物车元数据(上面在 #2 中创建)添加到订单中

  4. 根据自定义价格元调整产品的成本(在上面的 #3 中添加)。


第 1 步:添加自定义输入字段:

您可以使用woocommerce_before_add_to_cart_button过滤器添加输入字段,如下所示。

或者,您可以使用woocommerce_wp_text_input-这是一个示例

add_action( 'woocommerce_before_add_to_cart_button', 'add_custom_price_input', 100 );

function add_custom_price_input() {

    if(get_the_ID() != 123) { //use the product ID of your gift card here, otherwise all products will get this additional field

        return;

    }

    echo '<input type="number" min="50" placeholder="50" name="so_57140247_price">';

}

第 2 步:将自定义价格保存到购物车/会话

接下来,我们需要确保您的自定义输入字段数据被转移到购物车/会话数据。我们可以使用woocommerce_add_cart_item_data docs | example )过滤器:

add_filter( 'woocommerce_add_cart_item_data', 'add_custom_meta_to_cart', 10, 3 );

function add_custom_meta_to_cart( $cart_item_data, $product_id, $variation_id ) {

    $custom_price   = intval(filter_input( INPUT_POST, 'so_57140247_price' ));


    if ( !empty( $custom_price ) && $product_id == 123 ) { //check that the custom_price variable is set, and that the product is your gift card

        $cart_item_data['so_57140247_price'] = $custom_price; //this will add your custom price data to the cart item data

    }


    return $cart_item_data;

}

第 3 步:将购物车元添加到订单中

接下来,我们必须将购物车/会话中的元添加到订单本身,以便它可以用于订单总额计算。我们使用woocommerce_checkout_create_order_line_item docs | example )来做到这一点:

add_action( 'woocommerce_checkout_create_order_line_item', 'add_custom_meta_to_order', 10, 4 );

function add_custom_meta_to_order( $item, $cart_item_key, $values, $order ) {

    //check if our custom meta was set on the line item of inside the cart/session

    if ( !empty( $values['so_57140247_price'] ) ) {

        $item->add_meta_data( '_custom_price', $values['so_57140247_price'] ); //add the value to order line item

    }

    return;

}

第 4 步:调整礼品卡订单项的总数

最后,我们根据输入字段中输入的值简单地调整礼品卡行项目的成本。我们可以挂钩woocommerce_before_calculate_totals docs | example来做到这一点。

add_action( 'woocommerce_before_calculate_totals', 'calculate_cost_custom', 10, 1);

function calculate_cost_custom( $cart_obj ) {

    foreach ( $cart_obj->get_cart() as $key => $value ) {

        $price      = intval($value['_custom_price']);

        $value['data']->set_price( $price );

    }

}


查看完整回答
反对 回复 2021-10-22
  • 1 回答
  • 0 关注
  • 114 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信