So I was trying to create a woocommerce shipping method that takes the cart subtotal and charges a user-defined percentage of the cart subtotal as a shipping fee. As a first step towards this goal, ehat I did was basically like this
class Subtotal_Percentage_Method extends WC_Shipping_Method {
// to store percentage
private $percentage_rate
// constructor that handles settings
// here is where i start calculation
public function calculate_shipping($packages = array()) {
$cost = $this->percentage_rate * 1000;
add_rate(array(
'id' => $this->id,
'label' => $this->title,
'cost' => $cost
));
}
}
This one works. However, it doesn't work when I change the calculate_shipping method to use the cart subtotal in the calculation like this
public function calculate_shipping($packages = array()) {
$subtotal = WC()->cart->subtotal;
$cost = $subtotal * $this->percentage_rate / 100;
add_rate(array(
'id' => $this->id,
'label' => $this->title,
'cost' => $cost
));
}
Can anyone show me what I'm doing wrong?