I’m writing a plugin for WooCommerce that creates a custom shipping option using my own algorithm.
I’m new to object oriented programming though, and am a big confused on how to properly access methods/classes outside of the one I’m in.
Right now there is a class called calculate_shipping() that WooCommerce uses. Basically, my new shipping method extends the WC_Shipping_Method class to add this new one.
My question is this:
Within my_new_shipping_class()->calculate_shipping()
, what’s the correct way to query the following?
- Return a list of all products in the shopping cart array and their associated weight
- Access the current zip code that the user has entered in their cart
From some digging I know there is an array called $cart_contents that seems to contain everything I need. (maybe not the weight though?)
This is under WC_Cart->get_cart()
, though there is also some kind of public array called $cart_contents. What is the correct way to access either of these?
Individual product weights can also be found under WC_Product->get_weight()
, but I’m not sure if I have to use that.
Ultimately, what I’m looking to return is a sorted array of each product weight. For example, say the cart has the following:
- Item 1, QTY: 1, 2lbs each
- Item 2, QTY: 2, 5lbs each
- Item 3, QTY: 1, 10lbs each
I’d like to return an array with [10,5,5,2] so I can then run an algorithm that places those products in boxes with maximum weights and returns individual shipping costs on each box.
Most of this question is probably around basic object oriented programming, so sorry if it comes off as a dumb question.
In case anyone else is searching for information about this, this is what I came up with.
The
calculate_shipping
method has a$package
parameter that provides access to the information you need to calculate the shipping fee.$package['destination']
provides an array of address information, and I was able to access the postcode using$package['destination']['postcode']
.$package['contents']
provides access to the array of items in the cart (keyed by the cart item id). Within each item, there is adata
array element which is the WC_Product instance. Here is how I was able to access all the product weights: