是否可以定制价格?

Posted

技术标签:

【中文标题】是否可以定制价格?【英文标题】:Is there a possibility to make custom prices? 【发布时间】:2019-07-22 06:27:46 【问题描述】:

我正在 Wordpress 上通过 WooCommerce 销售礼品卡。我的客户应该能够自己设置礼品卡金额的值。我只是能够通过插件做到这一点。是否有可能通过更改一些代码或通过functions.php来做到这一点?

已安装 Pimwick 礼品卡专业版

【问题讨论】:

【参考方案1】:

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

    向产品添加自定义输入字段以添加自定义价格 将该产品添加到购物车时,将自定义输入字段中的数据保存到会话(购物车) 在创建订单时将购物车元数据(在上面 #2 中创建)添加到订单中 根据自定义价格元调整产品成本(在上面的 #3 中添加)。

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

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

您也可以使用woocommerce_wp_text_input - here's an example

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 );
    

【讨论】:

以上是关于是否可以定制价格?的主要内容,如果未能解决你的问题,请参考以下文章

北京支付宝小程序开发价格

每日、每周、每月套餐的价格选项

一个微信小程序价格大概是多少

开发一款app系统软件价格大概需要多少钱呢

支付宝小程序微信小程序都可以找第三方开发嘛

做一个小程序大概需要多少钱?