One of the things any good framework should do is provide utility functions. Things that make developing for that framework easier and consistent. For an e-commerce framework that would be things like rounding prices, calculating taxes, and getting shipping quotes. If you've ever wanted to dig into WooCommerce there's a really easy guide to creating your own shipping method and I highly recommend you start there. It also happens to be a lot easier than building your own payment gateway. 🙂
I'm going to be talking about several of these useful utility functions that I used (and you'll also probably use) while building a custom shipping method.
Getting a Products Weight
Getting a products weight isn't too hard. If you're using the shipping method api guide you'll get a list of packages in the
Now there's one problem with the snippet above. We're just pulling the numerical value for the weight entered into the backend. This doesn't take into account any sort of unit. It could be feet, inches, centimeters, or anything really! That's where one of these handy utility functions comes in.
wc_get_weight() is a function that will automatically convert those units for you! So after fetching the weight just call this function and enter the desired measurement unit and you'll get it back in that format. See the function documentation for the exact syntax. Easy piesy.
Getting a Products Dimensions
The same thing goes for getting a products dimensions. You can use the same loop above but instead of using
$values[‘data']->get_weight() just use
$values[‘data']->height (notice the lack of parenthesis – these are not functions they're attributes). Just like with the weight you'll need to make sure you're using the right units.
wc_get_dimension() is a function that will convert those units for you. Pass in any number and the desired units and it will convert it for you.
Making Shipping Methods Easier to Create
I love little utility functions like this. They make my life so much easier. I'm just finishing up a custom shipping method for a client and with just two extra lines of code I was able to make sure that this custom method works no matter what units they choose to use in the backend.