Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get All Shipping Classes in Woocommerce 3

I've been unable to crack this nut, but can't help feel that I'm missing something simple.

I'm developing a WooCommerce plugin that should provide a list of shipping classes on its admin settings page. The following code as suggested in another question's answer indicated that the following should work:

$shipping           = new \WC_Shipping();
$shipping_classes   = $shipping->get_shipping_classes();
var_dump($shipping_classes);
die();

Unfortunately the output is an empty array.

I am using Wordpress 4.9.5 and WooCommerce 3.3.5. Thanks for any help!

UPDATE I have the exact same problem as outlined here: get_terms() returns Invalid Taxonomy and have provided a work-around. However, I do not feel that is a solution.

like image 437
mike.bronner Avatar asked Apr 15 '18 16:04

mike.bronner


1 Answers

To get all the shipping classes you just need the following:

$shipping_classes = get_terms( array('taxonomy' => 'product_shipping_class', 'hide_empty' => false ) );

Tested and works. This will give you an array of the WP_Term objects of all shipping classes.

In Woocommerce the shipping classes are under product_shipping_class custom taxonomy.


Or you can use this custom function with a simple SQL query:

function wc_get_shipping_classes(){
    global $wpdb;
    $return $wpdb->get_results( "
        SELECT * FROM {$wpdb->prefix}terms as t
        INNER JOIN {$wpdb->prefix}term_taxonomy as tt ON t.term_id = tt.term_id
        WHERE tt.taxonomy LIKE 'product_shipping_class'
    " );
}

Code goes in function.php file of your active child theme (or active theme).

USAGE (test example):

$shipping_classes = wc_get_shipping_classes(); // Get Shipping Classes
echo '<pre>'; print_r($shipping_classes); echo '</pre>'; // Test raw output   
like image 158
LoicTheAztec Avatar answered Oct 19 '22 23:10

LoicTheAztec