首页 \ 问答 \ 根据Woocommerce中的自定义字段计算自定义购物车商品价格(Custom cart item price calculation based on dimentions custom fields in Woocommerce)

根据Woocommerce中的自定义字段计算自定义购物车商品价格(Custom cart item price calculation based on dimentions custom fields in Woocommerce)

我在woocommerce单个产品页面中创建了一些输入自定义字段,用户可以分别输入高度和宽度值...当产品添加到购物车时,自定义字段值也显示在购物车和结帐页面中。

示例:如果用户输入高度='15'且宽度='20',则其显示为购物车页面,如height = 15 width = 20

单品页面

单品页面

购物车页面

购物车页面

现在Iém试图实现的是根据“高度”和“宽度”自定义字段值进行自定义价格计算:

总价=(高/ 3 *宽/ 30 + 3)* 1.48

最终计算的价格应更新购物车商品价格。 但我无法实现这一部分,或者我不知道如何实现它。

这是我的代码:

/*
 * Display input on single product page
 * @return html
 */
function kia_satish_option(){
    $value = isset( $_POST['_satish_option'] ) ? sanitize_wp_checkbox( $_POST['_satish_option'] ) : '';
    printf( '<label>%s</label><input name="_satish_option" value="%s" type="number"/>', __( 'Height', 'kia-plugin-textdomain' ), esc_attr( $value ) );
}
add_action( 'woocommerce_before_add_to_cart_button', 'kia_satish_option', 9 );

function kia_satisher_option(){
    $value = isset( $_POST['_satisher_option'] ) ? sanitize_wp_checkbox( $_POST['_satisher_option'] ) : '';
    printf( '<label>%s</label><input name="_satisher_option" value="%s" type="number"/>', __( 'width', 'kia-plugin-textdomain' ), esc_attr( $value ) );
}
add_action( 'woocommerce_before_add_to_cart_button', 'kia_satisher_option', 9 );


function kia_yard_option(){
    $value = isset( $_POST['_yard_option'] ) ? sanitize_wp_checkbox( $_POST['_yard_option'] ) : '';
    printf( '<label>%s</label><input name="_yard_option" value="%s" type="number"/>', __( 'yard', 'kia-plugin-textdomain' ), esc_attr( $value ) );
}
add_action( 'woocommerce_before_add_to_cart_button', 'kia_yard_option', 9 );



/*
 * Add custom data to the cart item
 * @param array $cart_item
 * @param int $product_id
 * @return array
 */
function kia_add_cart_item_data( $cart_item, $product_id ){

    if( isset( $_POST['_satish_option'] ) ) {
        $cart_item['satish_option'] = sanitize_text_field( $_POST['_satish_option'] );
    }

    if( isset( $_POST['_satisher_option'] ) ) {
        $cart_item['satisher_option'] = sanitize_text_field( $_POST['_satisher_option'] );
    }

    if( isset( $_POST['_yard_option'] ) ) {
        $cart_item['yard_option'] = sanitize_text_field( $_POST['_yard_option'] );
    }

    return $cart_item;

}
add_filter( 'woocommerce_add_cart_item_data', 'kia_add_cart_item_data', 10, 2 );


/*
 * Load cart data from session
 * @param array $cart_item
 * @param array $other_data
 * @return array
 */
function kia_get_cart_item_from_session( $cart_item, $values ) {

    if ( isset( $values['satish_option'] ) ){
        $cart_item['satish_option'] = $values['satish_option'];
    }

    if ( isset( $values['satisher_option'] ) ){
        $cart_item['satisher_option'] = $values['satisher_option'];
    }

    if ( isset( $values['yard_option'] ) ){
        $cart_item['yard_option'] = $values['yard_option'];
    }

    return $cart_item;

}
add_filter( 'woocommerce_get_cart_item_from_session', 'kia_get_cart_item_from_session', 20, 2 );





/*
 * Add meta to order item
 * @param int $item_id
 * @param array $values
 * @return void
 */
function kia_add_order_item_meta( $item_id, $values ) {

    if ( ! empty( $values['satish_option'] ) ) {
        woocommerce_add_order_item_meta( $item_id, 'satish_option', $values['satish_option'] );           
    }

    if ( ! empty( $values['satisher_option'] ) ) {
        woocommerce_add_order_item_meta( $item_id, 'satisher_option', $values['satisher_option'] );           
    }
}
add_action( 'woocommerce_add_order_item_meta', 'kia_add_order_item_meta', 10, 2 );




/*
 * Get item data to display in cart
 * @param array $other_data
 * @param array $cart_item
 * @return array
 */
function kia_get_item_data( $other_data, $cart_item ) {

    if ( isset( $cart_item['satish_option'] ) ){

        $other_data[] = array(
            'name' => __( 'height', 'kia-plugin-textdomain' ),
            'value' => sanitize_text_field( $cart_item['satish_option'] )
        );

    }

    if ( isset( $cart_item['satisher_option'] ) ){

        $other_data[] = array(
            'name' => __( 'width', 'kia-plugin-textdomain' ),
            'value' => sanitize_text_field( $cart_item['satisher_option'] )
        );

    }

    if ( isset( $cart_item['yard_option'] ) ){

        $other_data[] = array(
            'name' => __( 'Yard', 'kia-plugin-textdomain' ),
            'value' => sanitize_text_field( $cart_item['yard_option'] )
        );

    }

    return $other_data;

}
add_filter( 'woocommerce_get_item_data', 'kia_get_item_data', 10, 2 );

我尝试通过以下代码实现公式部分:

    function woo_add_custom_general_fields_save($post_id)
{
    $woocommerce_product_height = $_POST['_product_height'];
    $woocommerce_product_width = $_POST['_product_width'];
    $woocommerce_final_price = $_POST['_final_price'];


// calculate and save _product_area_price, _regular_price, price as Height*Width
    if (!empty($woocommerce_product_height) && !empty($woocommerce_product_width)))
        $woocommerce_final_price = $woocommerce_product_height * $woocommerce_product_width ;

但它不起作用......

如何根据自定义购物车数据自定义计算更改购物车商品价格?


I have created some input custom fields in woocommerce single product pages where user can input height and width values respectively… When product is added to cart that custom fields values are displays in cart and checkout page too.

Example: if user input height='15' and width='20' then its display is cart page like height=15 width=20

single product page

single product page

cart page

cart page

Now what Iém trying to achieve is to make a custom price calculation based on that "height" and "width" custom fields values:

total price = (height/3 * width/30 + 3)*1.48

The final calculated price should update cart item price. But I'm unable to achieve this section or I dont know how to achieve it.

Here is my code:

/*
 * Display input on single product page
 * @return html
 */
function kia_satish_option(){
    $value = isset( $_POST['_satish_option'] ) ? sanitize_wp_checkbox( $_POST['_satish_option'] ) : '';
    printf( '<label>%s</label><input name="_satish_option" value="%s" type="number"/>', __( 'Height', 'kia-plugin-textdomain' ), esc_attr( $value ) );
}
add_action( 'woocommerce_before_add_to_cart_button', 'kia_satish_option', 9 );

function kia_satisher_option(){
    $value = isset( $_POST['_satisher_option'] ) ? sanitize_wp_checkbox( $_POST['_satisher_option'] ) : '';
    printf( '<label>%s</label><input name="_satisher_option" value="%s" type="number"/>', __( 'width', 'kia-plugin-textdomain' ), esc_attr( $value ) );
}
add_action( 'woocommerce_before_add_to_cart_button', 'kia_satisher_option', 9 );


function kia_yard_option(){
    $value = isset( $_POST['_yard_option'] ) ? sanitize_wp_checkbox( $_POST['_yard_option'] ) : '';
    printf( '<label>%s</label><input name="_yard_option" value="%s" type="number"/>', __( 'yard', 'kia-plugin-textdomain' ), esc_attr( $value ) );
}
add_action( 'woocommerce_before_add_to_cart_button', 'kia_yard_option', 9 );



/*
 * Add custom data to the cart item
 * @param array $cart_item
 * @param int $product_id
 * @return array
 */
function kia_add_cart_item_data( $cart_item, $product_id ){

    if( isset( $_POST['_satish_option'] ) ) {
        $cart_item['satish_option'] = sanitize_text_field( $_POST['_satish_option'] );
    }

    if( isset( $_POST['_satisher_option'] ) ) {
        $cart_item['satisher_option'] = sanitize_text_field( $_POST['_satisher_option'] );
    }

    if( isset( $_POST['_yard_option'] ) ) {
        $cart_item['yard_option'] = sanitize_text_field( $_POST['_yard_option'] );
    }

    return $cart_item;

}
add_filter( 'woocommerce_add_cart_item_data', 'kia_add_cart_item_data', 10, 2 );


/*
 * Load cart data from session
 * @param array $cart_item
 * @param array $other_data
 * @return array
 */
function kia_get_cart_item_from_session( $cart_item, $values ) {

    if ( isset( $values['satish_option'] ) ){
        $cart_item['satish_option'] = $values['satish_option'];
    }

    if ( isset( $values['satisher_option'] ) ){
        $cart_item['satisher_option'] = $values['satisher_option'];
    }

    if ( isset( $values['yard_option'] ) ){
        $cart_item['yard_option'] = $values['yard_option'];
    }

    return $cart_item;

}
add_filter( 'woocommerce_get_cart_item_from_session', 'kia_get_cart_item_from_session', 20, 2 );





/*
 * Add meta to order item
 * @param int $item_id
 * @param array $values
 * @return void
 */
function kia_add_order_item_meta( $item_id, $values ) {

    if ( ! empty( $values['satish_option'] ) ) {
        woocommerce_add_order_item_meta( $item_id, 'satish_option', $values['satish_option'] );           
    }

    if ( ! empty( $values['satisher_option'] ) ) {
        woocommerce_add_order_item_meta( $item_id, 'satisher_option', $values['satisher_option'] );           
    }
}
add_action( 'woocommerce_add_order_item_meta', 'kia_add_order_item_meta', 10, 2 );




/*
 * Get item data to display in cart
 * @param array $other_data
 * @param array $cart_item
 * @return array
 */
function kia_get_item_data( $other_data, $cart_item ) {

    if ( isset( $cart_item['satish_option'] ) ){

        $other_data[] = array(
            'name' => __( 'height', 'kia-plugin-textdomain' ),
            'value' => sanitize_text_field( $cart_item['satish_option'] )
        );

    }

    if ( isset( $cart_item['satisher_option'] ) ){

        $other_data[] = array(
            'name' => __( 'width', 'kia-plugin-textdomain' ),
            'value' => sanitize_text_field( $cart_item['satisher_option'] )
        );

    }

    if ( isset( $cart_item['yard_option'] ) ){

        $other_data[] = array(
            'name' => __( 'Yard', 'kia-plugin-textdomain' ),
            'value' => sanitize_text_field( $cart_item['yard_option'] )
        );

    }

    return $other_data;

}
add_filter( 'woocommerce_get_item_data', 'kia_get_item_data', 10, 2 );

I tried to achieve formula section by code below:

    function woo_add_custom_general_fields_save($post_id)
{
    $woocommerce_product_height = $_POST['_product_height'];
    $woocommerce_product_width = $_POST['_product_width'];
    $woocommerce_final_price = $_POST['_final_price'];


// calculate and save _product_area_price, _regular_price, price as Height*Width
    if (!empty($woocommerce_product_height) && !empty($woocommerce_product_width)))
        $woocommerce_final_price = $woocommerce_product_height * $woocommerce_product_width ;

But it doesn't work…

How can I change the cart item price with a custom calculation based on custom cart data?


原文:https://stackoverflow.com/questions/49523416
更新时间:2019-12-13 07:40

最满意答案

我完全重新审视了你的代码,删除了一些小东西,重命名了其他代码并添加了缺少的部分......

你的计算看起来很奇怪:

$total_price = ($height/3 * $width/30 + 3)*1.48;

一切正常,如果需要,您将能够轻松更改计算...

代码:

// Display custom input fields in single product page
add_action( 'woocommerce_before_add_to_cart_button', 'add_product_custom_fields', 20 );
function add_product_custom_fields(){
    $domain =  'woocommerce';
    $value = isset( $_POST['height_option'] ) ? sanitize_key( $_POST['height_option'] ) : '';
    printf( '<label>%s</label><input name="height_option" value="%s" type="number"/><br>', __( 'Height', $domain ), esc_attr( $value ) );

    $value = isset( $_POST['width_option'] ) ? sanitize_key( $_POST['width_option'] ) : '';
    printf( '<label>%s</label><input name="width_option" value="%s" type="number"/><br>', __( 'Width', $domain ), esc_attr( $value ) );
}

// Add custom fields data to cart items and make calculation price
add_filter( 'woocommerce_add_cart_item_data', 'custom_add_cart_item_data', 20, 2 );
function custom_add_cart_item_data( $cart_item, $product_id ){

    if( isset( $_POST['height_option'] ) )
        $cart_item['custom_data']['height'] = sanitize_key( $_POST['height_option'] );

    if( isset( $_POST['width_option'] ) )
        $cart_item['custom_data']['width'] = sanitize_key( $_POST['width_option'] );

    // Make calculation and save calculated  price
    if( isset( $_POST['height_option'] ) && isset( $_POST['width_option'] ) ){
        $height      = (int) sanitize_key( $_POST['height_option'] );
        $width       = (int) sanitize_key( $_POST['width_option'] );

        if( $width > 0 && $height > 0 ){
            $total_price = ( ( $height / 3 ) * ( $width / 30 ) + 3 ) * 1.48; // <== The calculation
            $cart_item['custom_data']['price'] = round($total_price, 2); // Save the price in the custom data
        }
    }

    return $cart_item;
}

// Display custom data in cart and checkout pages
add_filter( 'woocommerce_get_item_data', 'display_custom_cart_item_data', 10, 2 );
function display_custom_cart_item_data( $cart_data, $cart_item ) {
    $domain = 'woocommerce';

    if ( isset( $cart_item['custom_data']['height'] ) ){
        $cart_data[] = array(
            'name' => __( 'Height', $domain ),
            'value' => $cart_item['custom_data']['height']
        );
    }
    if ( isset( $cart_item['custom_data']['width'] ) ){
        $cart_data[] = array(
            'name' => __( 'Width', $domain ),
            'value' => $cart_item['custom_data']['width']
        );
    }
    return $cart_data;
}

// Set the new calculated price replacing cart item price
add_action( 'woocommerce_before_calculate_totals', 'set_cart_item_calculated_price', 20, 1 );
function set_cart_item_calculated_price( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ){
        if( ! isset( $cart_item['custom_data']['price'] ) ){
            continue;
        }
        if( $cart_item['custom_data']['price'] > 0 ){
            // Set the calculated item price (if there is one)
            $cart_item['data']->set_price( (float) $cart_item['custom_data']['price'] );
        }
    }
}


// Get cart item custom data and update order item meta and display in orders and emails
add_action( 'woocommerce_checkout_create_order_line_item', 'save_order_item_custom_meta_data', 10, 2 );
function custom_add_order_item_meta( $item_id, $values ) {
    $domain = 'woocommerce';

    if( isset( $cart_item['custom_data']['height'] ) )
        $item->update_meta_data( __( 'Height', $domain ), $values['custom_data']['height'] );

    if( isset( $cart_item['custom_data']['width'] ) )
        $item->update_meta_data( __( 'Width', $domain ), $values['custom_data']['width'] );
}

代码位于活动子主题(或活动主题)的function.php文件中。 经过测试和工作。


I have revisited completely your code, removed some little things, renamed others and added missing parts…

Yours calculation looks very strange:

$total_price = ($height/3 * $width/30 + 3)*1.48;

As everything works, you will be able to make easily changes in your calculation if needed…

The code:

// Display custom input fields in single product page
add_action( 'woocommerce_before_add_to_cart_button', 'add_product_custom_fields', 20 );
function add_product_custom_fields(){
    $domain =  'woocommerce';
    $value = isset( $_POST['height_option'] ) ? sanitize_key( $_POST['height_option'] ) : '';
    printf( '<label>%s</label><input name="height_option" value="%s" type="number"/><br>', __( 'Height', $domain ), esc_attr( $value ) );

    $value = isset( $_POST['width_option'] ) ? sanitize_key( $_POST['width_option'] ) : '';
    printf( '<label>%s</label><input name="width_option" value="%s" type="number"/><br>', __( 'Width', $domain ), esc_attr( $value ) );
}

// Add custom fields data to cart items and make calculation price
add_filter( 'woocommerce_add_cart_item_data', 'custom_add_cart_item_data', 20, 2 );
function custom_add_cart_item_data( $cart_item, $product_id ){

    if( isset( $_POST['height_option'] ) )
        $cart_item['custom_data']['height'] = sanitize_key( $_POST['height_option'] );

    if( isset( $_POST['width_option'] ) )
        $cart_item['custom_data']['width'] = sanitize_key( $_POST['width_option'] );

    // Make calculation and save calculated  price
    if( isset( $_POST['height_option'] ) && isset( $_POST['width_option'] ) ){
        $height      = (int) sanitize_key( $_POST['height_option'] );
        $width       = (int) sanitize_key( $_POST['width_option'] );

        if( $width > 0 && $height > 0 ){
            $total_price = ( ( $height / 3 ) * ( $width / 30 ) + 3 ) * 1.48; // <== The calculation
            $cart_item['custom_data']['price'] = round($total_price, 2); // Save the price in the custom data
        }
    }

    return $cart_item;
}

// Display custom data in cart and checkout pages
add_filter( 'woocommerce_get_item_data', 'display_custom_cart_item_data', 10, 2 );
function display_custom_cart_item_data( $cart_data, $cart_item ) {
    $domain = 'woocommerce';

    if ( isset( $cart_item['custom_data']['height'] ) ){
        $cart_data[] = array(
            'name' => __( 'Height', $domain ),
            'value' => $cart_item['custom_data']['height']
        );
    }
    if ( isset( $cart_item['custom_data']['width'] ) ){
        $cart_data[] = array(
            'name' => __( 'Width', $domain ),
            'value' => $cart_item['custom_data']['width']
        );
    }
    return $cart_data;
}

// Set the new calculated price replacing cart item price
add_action( 'woocommerce_before_calculate_totals', 'set_cart_item_calculated_price', 20, 1 );
function set_cart_item_calculated_price( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ){
        if( ! isset( $cart_item['custom_data']['price'] ) ){
            continue;
        }
        if( $cart_item['custom_data']['price'] > 0 ){
            // Set the calculated item price (if there is one)
            $cart_item['data']->set_price( (float) $cart_item['custom_data']['price'] );
        }
    }
}


// Get cart item custom data and update order item meta and display in orders and emails
add_action( 'woocommerce_checkout_create_order_line_item', 'save_order_item_custom_meta_data', 10, 2 );
function custom_add_order_item_meta( $item_id, $values ) {
    $domain = 'woocommerce';

    if( isset( $cart_item['custom_data']['height'] ) )
        $item->update_meta_data( __( 'Height', $domain ), $values['custom_data']['height'] );

    if( isset( $cart_item['custom_data']['width'] ) )
        $item->update_meta_data( __( 'Width', $domain ), $values['custom_data']['width'] );
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

2018-10-01

相关文章

更多

最新问答

更多
  • 这个listArray是如何填充的?(How is this listArray populated?)
  • iOS 7上的CTSubscriber(以及如何使用它)是什么?(What's CTSubscriber (and how to use it) on iOS 7?)
  • 手动创建VisualStudio 2012项目文件(Manually creating VisualStudio 2012 project file)
  • 删除不适用于JSP中使用for循环的每个id(Deletion not working for every id using for loop in JSP)
  • 如何从std :: filesystem :: path中删除引号(How to remove quotation marks from std::filesystem::path)
  • 验证多个控制器方法的URL路径(Validate URL path for several controller methods)
  • 如何在datarow []中的列中找到最大值?(How to find max value in a column in a datarow[] ?)
  • 如何使用预定义文本替换来自数据库的部分结果(How do I replace part of result coming from Database with predefined text)
  • Selenium Java注入了新的Javascript函数(Selenium Java inject new Javascript function)
  • 使用.on的多个下拉菜单选择文本仅适用于第一个下拉列表(Multiple Dropdowns Menu Selection text using .on works only on first dropdown)
  • 快速将黄土曲线添加到大型数据集图中的方法(Quick way to add loess curve to large data set graph)
  • FilteringSelect in mvc(FilteringSelect in mvc)
  • 在Delphi XE2中开发Mac或iOS应用程序需要哪些硬件/软件?(What hardware/software is necessary to develop Mac or iOS apps in Delphi XE2?)
  • 在原型的构造函数中初始化属性时获取“未定义”(Getting 'undefined' when a property is initialized in the constructor of a prototype)
  • 通过越狱加载的应用程序的Documents文件夹位置(Location of Documents folder for an app loaded via jailbreak)
  • 在OpenGL中使用可编程和固定管道功能(Using both programmable and fixed pipeline functionality in OpenGL)
  • 将任何用户输入重定向到单独的底层程序(redirect any user input to a separate underlying program)
  • 编辑文本不能正常工作android(Edit texts not working properly android)
  • “user_denied”Facebook应用页面上的Facebook用户区域设置(Facebook user locale on “user_denied” facebook app page)
  • 在大图像中找到小的部分透明图像的坐标(find coordinates of small partially-transparent image within a large image)
  • 我如何在cakephp 3.1中获得完整的相对路径?(How i can get full relative path of image in cakephp 3.1?)
  • 如何保存拖动标记的新本地化?(How to save new localization of dragged marker?)
  • MySQL UPDATE vs INSERT和DELETE(MySQL UPDATE vs INSERT and DELETE)
  • 在执行查询之前,在SQLAlchemy模型中将datetime转换为unix时间戳?(Convert datetime to unix timestamp in SQLAlchemy model before executing query?)
  • OpenCL与OpenGL互操作的优势(Advantage of OpenCL interoperability with OpenGL)
  • 如何解析用点和等分隔的数据然后添加到listview(How to parsing data from delimited with dot and equal then add to listview)
  • 带调试输出的X3解析器段错误(BOOST_SPIRIT_X3_DEBUG)(X3 parser segfaults with debug output (BOOST_SPIRIT_X3_DEBUG))
  • 将文件夹名称添加到fgrep结果(Add folder name to fgrep result)
  • 在MySQL中加载一个表是非常慢的(Loading one table in MySQL is ridiculously slow)
  • 如何将JSON放入PHP变量?(How do I put JSON into a PHP Variable?)