douduan9391 2018-04-12 22:40
浏览 109
已采纳

使用产品自定义字段值覆盖woocommerce购物车商品价格

In woocommerce I am using Advanced Custom Fields and trying to get a custom field value in each product as price instead of the default product price. this custom field is called 'custom_price'.

How can I change this hard coded value to use that instead?

Here is my code:

 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);
     }
 }
  • 写回答

1条回答 默认 最新

  • doubi4814 2018-04-12 23:23
    关注

    Update 3: Here is the complete solution with all custom fields and the cart item price change.

    You will need to add some jQuery code to make your product price calculation, display calculated price on product page and set this calculated price on a hidden field.

    Once product will be added to cart, the code will catch the calculated price and will set it in the corresponding cart item…

    The code:

    // 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'] );
        }
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works (but you will need to make your own calculations with jquery)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R