php - 用产品自定义字段值覆盖 woocommerce 购物车项目价格

标签 php wordpress woocommerce cart custom-fields

在 woocommerce 中,我使用高级自定义字段并尝试在每个产品中获取自定义字段值作为价格而不是默认产品价格。此自定义字段称为 'custom_price'

如何更改此硬编码值以改为使用它?

这是我的代码:

 add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' 
 );

 function add_custom_price( $cart_object ) {
     $custom_price = 10; 
     foreach ( $cart_object->cart_contents as $key => $value ) {
         $value['data']->set_price($custom_price);
     }
 }

最佳答案

更新 3:这是包含所有自定义字段和购物车商品价格变化的完整解决方案。

您将需要添加一些 jQuery 代码来计算产品价格,在产品页面上显示计算价格并将计算价格设置在隐藏字段上。

一旦将产品添加到购物车,代码将捕获计算出的价格并将其设置在相应的购物车项目中......

代码:

// The product custom field - Frontend
add_action( 'woocommerce_before_add_to_cart_button', 'custom_discount_price_product_field' );
function custom_discount_price_product_field() {
    global $product;

    $curs = get_woocommerce_currency_symbol(); // Currency symbol

    // Get the discounted value (from product backend)
    $discount = (float) get_post_meta( $product->get_id(), '_price_discount', true );

    // jQuery will get the discount here for calculations
    echo '<input type="hidden" name="price_discount" value="'.$discount.'">';

    echo '<div>';

    woocommerce_form_field( 'select_price', array(
        'type'          => 'select',
        'class'         => array('my-field-class form-row-wide'),
        'label'         => __('Discount'),
        'options'     => array(
            ''      => __( 'Select your discount', 'woocommerce' ),
            '5'     => $curs . '5',
            '10'    => $curs . '10',
            '15'    => $curs . '15',
            '20'    => $curs . '20',
        ),
    ), '' );

    // This field will be used to send the calculated price
    // jQuery will set the calculated price on this field
    echo '<input type="hidden" name="custom_price" value="52">'; // 52 is a fake value for testing purpose

    echo '</div><br>';

    // BELOW your jquery code to calculate price and update "custom_price" hidden field
    ?>
    <script type="text/javascript">
    jQuery( function($){
        // Here
    });
    </script>
    <?php
}

// Add a custom field to product in backend
add_action( 'woocommerce_product_options_pricing', 'add_field_product_options_pricing' );
function add_field_product_options_pricing() {
    global $post;

    echo '<div class="options_group">';

    woocommerce_wp_text_input( array(
        'id'            => '_price_discount',
        'label'         => __('Discount price', 'woocommerce') . ' (%)',
        'placeholder'   => __('Set the Discount price…', 'woocommerce'),
        'description'   => __('Enter the custom value here.', 'woocommerce'),
        'desc_tip'      => 'true',
    ));

    echo '</div>';
}

// Save product custom field to database when submitted in Backend
add_action( 'woocommerce_process_product_meta', 'save_product_options_custom_fields', 30, 1 );
function save_product_options_custom_fields( $post_id ){
    // Saving custom field value
    if( isset( $_POST['_price_discount'] ) ){
        update_post_meta( $post_id, '_price_discount', sanitize_text_field( $_POST['_price_discount'] ) );
    }
}

// Add custom calculated price conditionally as custom data to cart items
add_filter( 'woocommerce_add_cart_item_data', 'add_custom_price_to_cart_item_data', 20, 2 );
function add_custom_price_to_cart_item_data( $cart_item_data, $product_id ){
    if( ! isset($_POST['custom_price']) )
        return $cart_item_data;

    $cart_item_data['custom_price'] = (float) sanitize_text_field( $_POST['custom_price'] );
    $cart_item_data['unique_key'] = md5( microtime() . rand() ); // Make each item unique

    return $cart_item_data;
}

// Set conditionally a custom item price
add_action('woocommerce_before_calculate_totals', 'set_cutom_cart_item_price', 20, 1);
function set_cutom_cart_item_price( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

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

    foreach (  $cart->get_cart() as $cart_item ) {
        if ( isset( $cart_item['custom_price'] ) )
            $cart_item['data']->set_price( $cart_item['custom_price'] );
    }
}

代码进入事件子主题(或事件主题)的 function.php 文件。经过测试并有效(但您需要使用 jquery 进行自己的计算)

关于php - 用产品自定义字段值覆盖 woocommerce 购物车项目价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49806877/

相关文章:

php - 如何使用 PHP 开发音乐流媒体网站

html - 通过在不同服务器上托管图像来提高加载性能

javascript - 我可以从我的网站删除这个文件 "html5shiv.googlecode.com/svn/trunk/html5.js"吗?

php - 使用单选按钮和连接表获取 MySQL 数据

javascript - 如何使用 jquery 或 php 根据条件闪烁表行?

javascript - 如何使 slider 图像变暗?

css - 如何将 Bootstrap 与 wordpress 和 woocommerce 一起使用?

php - 根据 WooCommerce 中的自定义结帐单选按钮和文本字段设置动态费用

php - 在 WooCommerce 订阅中获取用户 ID

php - 无查询结果