WC_Shipping_Legacy_Flat_Rate::calculate_shipping( array $package = array() )
Calculate shipping.
Description Description
Parameters Parameters
- $package
-
(Optional) (default: array()).
Default value: array()
Source Source
File: includes/shipping/legacy-flat-rate/class-wc-shipping-legacy-flat-rate.php
public function calculate_shipping( $package = array() ) {
$rate = array(
'id' => $this->id,
'label' => $this->title,
'cost' => 0,
'package' => $package,
);
// Calculate the costs.
$has_costs = false; // True when a cost is set. False if all costs are blank strings.
$cost = $this->get_option( 'cost' );
if ( '' !== $cost ) {
$has_costs = true;
$rate['cost'] = $this->evaluate_cost(
$cost,
array(
'qty' => $this->get_package_item_qty( $package ),
'cost' => $package['contents_cost'],
)
);
}
// Add shipping class costs.
$found_shipping_classes = $this->find_shipping_classes( $package );
$highest_class_cost = 0;
foreach ( $found_shipping_classes as $shipping_class => $products ) {
// Also handles BW compatibility when slugs were used instead of ids.
$shipping_class_term = get_term_by( 'slug', $shipping_class, 'product_shipping_class' );
$class_cost_string = $shipping_class_term && $shipping_class_term->term_id ? $this->get_option( 'class_cost_' . $shipping_class_term->term_id, $this->get_option( 'class_cost_' . $shipping_class, '' ) ) : $this->get_option( 'no_class_cost', '' );
if ( '' === $class_cost_string ) {
continue;
}
$has_costs = true;
$class_cost = $this->evaluate_cost(
$class_cost_string,
array(
'qty' => array_sum( wp_list_pluck( $products, 'quantity' ) ),
'cost' => array_sum( wp_list_pluck( $products, 'line_total' ) ),
)
);
if ( 'class' === $this->type ) {
$rate['cost'] += $class_cost;
} else {
$highest_class_cost = $class_cost > $highest_class_cost ? $class_cost : $highest_class_cost;
}
}
if ( 'order' === $this->type && $highest_class_cost ) {
$rate['cost'] += $highest_class_cost;
}
$rate['package'] = $package;
// Add the rate.
if ( $has_costs ) {
$this->add_rate( $rate );
}
/**
* Developers can add additional flat rates based on this one via this action since @version 2.4.
*
* Previously there were (overly complex) options to add additional rates however this was not user.
* friendly and goes against what Flat Rate Shipping was originally intended for.
*
* This example shows how you can add an extra rate based on this flat rate via custom function:
*
* add_action( 'woocommerce_flat_rate_shipping_add_rate', 'add_another_custom_flat_rate', 10, 2 );
*
* function add_another_custom_flat_rate( $method, $rate ) {
* $new_rate = $rate;
* $new_rate['id'] .= ':' . 'custom_rate_name'; // Append a custom ID.
* $new_rate['label'] = 'Rushed Shipping'; // Rename to 'Rushed Shipping'.
* $new_rate['cost'] += 2; // Add $2 to the cost.
*
* // Add it to WC.
* $method->add_rate( $new_rate );
* }.
*/
do_action( 'woocommerce_flat_rate_shipping_add_rate', $this, $rate );
}