Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

php - Add a custom product calculated price to Woocommerce cart

In woocommerce I have added an extra text field before add to cart button to add custom charge on product purchase.

This plugin will add extra text field to single product page and calculates total plus the extra charge.

My problem is that I cant add custom cart totals and the extra charge add before totals

I tried woocommerce_cart_calculate_fees but no luck it only show $0 in totals

PHP code:

 /**
 * Check if woocommerce is active and or installed.
 */

if ( class_exists( 'WooCommerce' ) || in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) || function_exists( 'WC' ) && is_object( WC() ) && is_a( WC(), 'WooCommerce' )  )
{

/**
 * Style and Ajax script.
 */
    add_action('woocommerce_single_product_summary','extra_enqueue_scripts');

        function  extra_enqueue_scripts()
        {
            wp_enqueue_style('custom_style', plugins_url('/assets/css/custom_style.css', __FILE__));

            wp_register_script( 'item_add', plugins_url('/assets/js/item_add.js', __FILE__), array('jquery'), false, true ); 
            wp_enqueue_script('item_add'); 

            $array_to_be_sent = array( 'ajax_file_path' => admin_url('admin-ajax.php')); 

            wp_localize_script( 'item_add', 'wdm_object', $array_to_be_sent);

        }


/**
 * Add Text field Before add to cart button.
 */     

    add_action( 'woocommerce_before_add_to_cart_button', 'extra_add_custom_field', 0 );

        function extra_add_custom_field() 
        {
          $currency = get_woocommerce_currency_symbol();
          echo "<div class='custom-text text'><p>Extra Charge ($currency):</p>
          <input type='text' name='custom_price' value='' placeholder='e.g. 10' title='Custom Text' class='custom_price text_custom text'></div>";

        } 

/**
 * Add ajax callback function to get data
 * and add that data to session.
 */             

    add_action('wp_ajax_extra_add_user_custom_data_options_callback', 'extra_add_user_custom_data_options_callback');
    add_action('wp_ajax_nopriv_extra_add_user_custom_data_options_callback', 'extra_add_user_custom_data_options_callback');

        function extra_add_user_custom_data_options_callback()
        {
          $user_custom_data_values = (float)sanitize_text_field($_POST['custom_price']);
          session_start();
          $_SESSION['user_custom_data'] = $user_custom_data_values;
          die();
        }


/**
 * Add data to cart from session and then destroy session.
 */ 

    add_filter('woocommerce_add_cart_item_data','extra_add_custom_field_data',1,2);

        function extra_add_custom_field_data($cart_item_data,$product_id)
        {
            global $woocommerce;
            session_start();    
            if (isset($_SESSION['user_custom_data'])) 
            {
                $option    = $_SESSION['user_custom_data'];       
                $new_value = array('user_custom_data_value' => $option);
            }
            if(empty($option))
            {               
                return $cart_item_data;
            }
            else
            {    
                if(empty($cart_item_data))
                {
                    return $new_value;
                }
                else
                {
                    return array_merge($cart_item_data,$new_value);
                }
            }
            unset($_SESSION['user_custom_data']); 
        }


/**
 * Derive cart Item from session.
 */         

    add_filter('woocommerce_get_cart_item_from_session', 'extra_get_cart_items_from_session', 1, 3 );

        function extra_get_cart_items_from_session($item,$values,$key)
        {
            if (array_key_exists( 'user_custom_data_value', $values ) )
            {
                $item['user_custom_data_value'] = $values['user_custom_data_value'];
            }       
            return $item;
        }

/** 
 * Add extra price into product regular price.
 * Calculate extra price before checkout.
 */         

    add_action( 'woocommerce_before_calculate_totals', 'extra_price_add_custom_price' );

        function extra_price_add_custom_price( $cart_object ) 
        {   
          foreach ( $cart_object->get_cart() as $hash => $value )       
          { 
            if(!empty($value['user_custom_data_value']) && $value['data']->is_on_sale())
            {   
                $newprice = $value['data']->get_sale_price() + $value['user_custom_data_value'];
                $value['data']->set_price((float)( $newprice ));
            }
            elseif(!empty($value['user_custom_data_value']))
            {
                $newprice = $value['data']->get_regular_price() + $value['user_custom_data_value'];
                $value['data']->set_price((float)( $newprice ));
            }
          }
        }


/**
 * Render extra charge in cart table.
 */         

    add_filter('woocommerce_checkout_cart_item_quantity','extra_add_user_custom_option_from_session_into_cart',1,3); 
    add_filter('woocommerce_cart_item_price','extra_add_user_custom_option_from_session_into_cart',1,3);

        function extra_add_user_custom_option_from_session_into_cart($product_name, $values, $cart_item_key )
        {
            if(count($values['user_custom_data_value']) > 0)
            {
                $currency      = get_woocommerce_currency_symbol();
                $product_price = wc_get_product( $values['product_id'] );
                if($product_price->is_on_sale())
                {
                    $price = $product_price->get_sale_price().'&nbsp;(On Sale!)';
                }
                else
                {
                    $price = $product_price->get_regular_price();
                }

                $custom_items  = $currency.$price."<br>";
                $custom_items .= $currency.$values['user_custom_data_value'].'&nbsp;';
                $custom_items .= __("Extra Charge", "woocommerce" );
                return $custom_items;
            }
            else
            {
                return $product_name;
            }
        }

/**
 * Remove custom data if quantity is zero.
 */ 

    add_action('woocommerce_before_cart_item_quantity_zero','extra_remove_user_custom_data_options_from_cart',1,1);

        function extra_remove_user_custom_data_options_from_cart($cart_item_key)
        {
            global $woocommerce;
            $cart = $woocommerce->cart->get_cart();
            foreach( $cart as $key => $values)
            {
                if ( $values['user_custom_data_value'] == $cart_item_key )
                {
                    unset( $woocommerce->cart->cart_contents[ $key ] );
                }
            }
        }       



/**
 * Add custom data to order meta after checkout.
 */ 

     add_action('woocommerce_add_order_item_meta','extra_add_values_to_order_item_meta',1,2);

        function extra_add_values_to_order_item_meta($item_id, $values)
        {
            global $woocommerce,$wpdb;
            $user_custom_values = $values['user_custom_data_value'];
            if(!empty($user_custom_values))
            {
                $currency = get_woocommerce_currency_symbol();
                wc_add_order_item_meta($item_id,'Extra Charge',$currency.$user_custom_values);  
            }
        }
} 

else 

{

/**
 * Generate error notice if woocommerce is not detected.
 */ 

    add_action( 'admin_notices', 'extra_no_woocommerce' );

        function extra_no_woocommerce()
        {
            $err_text = site_url()."/wp-admin/plugin-install.php?tab=plugin-information&plugin=woocommerce&TB_iframe=true";
            ?>
            <div class="error notice">
            <p><?php echo sprintf("Please Activate or <a href='%s' style='color:green;'>Install Woocommerce</a> to use extra field for product charge plugin",$err_text); ?></p>
            </div>
           <?php
        }
}

JS Code

jQuery(document).ready(function(){
        jQuery('.single_add_to_cart_button').click(function(){
          jQuery.ajax({
                    url: wdm_object.ajax_file_path,
                    type: "POST",
                    data: {
                            action:'add_user_custom_data_options_callback', 
                            custom_price : jQuery('.custom_price').val()
                          },
                    async : false,
                    success: function(data){
                        jQuery('.single_add_to_cart_button').text('Added to cart');
                    }
                });
 })
 });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You don't need any javascript or sessions to achieve that. Try the following revisited code instead:

// Add a custom field before single add to cart
add_action( 'woocommerce_before_add_to_cart_button', 'custom_product_price_field', 5 );
function custom_product_price_field(){
    echo '<div class="custom-text text">
    <p>Extra Charge ('.get_woocommerce_currency_symbol().'):</p>
    <input type="text" name="custom_price" value="" placeholder="e.g. 10" title="Custom Text" class="custom_price text_custom text">
    </div>';
}

// Get custom field value, calculate new item price, save it as custom cart item data
add_filter('woocommerce_add_cart_item_data', 'add_custom_field_data', 20, 2 );
function add_custom_field_data( $cart_item_data, $product_id ){
    if (! isset($_POST['custom_price']))
        return $cart_item_data;

    $custom_price = (float) sanitize_text_field( $_POST['custom_price'] );
    if( empty($custom_price) )
        return $cart_item_data;

    $product    = wc_get_product($product_id); // The WC_Product Object
    $base_price = (float) $product->get_regular_price(); // Product reg price

    // New price calculation
    $new_price = $base_price + $custom_price;

    // Set the custom amount in cart object
    $cart_item_data['custom_data']['extra_charge'] = (float) $custom_price;
    $cart_item_data['custom_data']['new_price'] = (float) $new_price;
    $cart_item_data['custom_data']['unique_key'] = md5( microtime() . rand() ); // Make each item unique

    return $cart_item_data;
}

// Set the new calculated cart item price
add_action( 'woocommerce_before_calculate_totals', 'extra_price_add_custom_price', 20, 1 );
function extra_price_add_custom_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_data']['new_price']) )
            $cart_item['data']->set_price( (float) $cart_item['custom_data']['new_price'] );
    }
}

// Display cart item custom price details
add_filter('woocommerce_cart_item_price', 'display_cart_items_custom_price_details', 20, 3 );
function display_cart_items_custom_price_details( $product_price, $cart_item, $cart_item_key ){
    if( isset($cart_item['custom_data']['extra_charge']) ) {
        $product = $cart_item['data'];
        $product_price  = wc_price( wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) ) );
        $product_price .= '<br>' . wc_price( $cart_item['custom_data']['extra_charge'] ).'&nbsp;';
        $product_price .= __("Extra Charge", "woocommerce" );
    }
    return $product_price;
}

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

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...