WC_AJAX::add_order_fee()

Add order fee via ajax.


Description Description


Source Source

File: includes/class-wc-ajax.php

	public static function add_order_fee() {
		check_ajax_referer( 'order-item', 'security' );

		if ( ! current_user_can( 'edit_shop_orders' ) ) {
			wp_die( -1 );
		}

		$response = array();

		try {
			$order_id = isset( $_POST['order_id'] ) ? absint( $_POST['order_id'] ) : 0;
			$order    = wc_get_order( $order_id );

			if ( ! $order ) {
				throw new Exception( __( 'Invalid order', 'woocommerce' ) );
			}

			$amount = isset( $_POST['amount'] ) ? wc_clean( wp_unslash( $_POST['amount'] ) ) : 0;

			$calculate_tax_args = array(
				'country'  => isset( $_POST['country'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['country'] ) ) ) : '',
				'state'    => isset( $_POST['state'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['state'] ) ) ) : '',
				'postcode' => isset( $_POST['postcode'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['postcode'] ) ) ) : '',
				'city'     => isset( $_POST['city'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['city'] ) ) ) : '',
			);

			if ( strstr( $amount, '%' ) ) {
				$formatted_amount = $amount;
				$percent          = floatval( trim( $amount, '%' ) );
				$amount           = $order->get_total() * ( $percent / 100 );
			} else {
				$amount           = floatval( $amount );
				$formatted_amount = wc_price( $amount, array( 'currency' => $order->get_currency() ) );
			}

			$fee = new WC_Order_Item_Fee();
			$fee->set_amount( $amount );
			$fee->set_total( $amount );
			/* translators: %s fee amount */
			$fee->set_name( sprintf( __( '%s fee', 'woocommerce' ), wc_clean( $formatted_amount ) ) );

			$order->add_item( $fee );
			$order->calculate_taxes( $calculate_tax_args );
			$order->calculate_totals( false );
			$order->save();

			ob_start();
			include 'admin/meta-boxes/views/html-order-items.php';
			$response['html'] = ob_get_clean();
		} catch ( Exception $e ) {
			wp_send_json_error( array( 'error' => $e->getMessage() ) );
		}

		// wp_send_json_success must be outside the try block not to break phpunit tests.
		wp_send_json_success( $response );
	}


Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.