Get All Shipping Classes in Woocommerce 3

mik*_*ner 5 php wordpress shipping custom-taxonomy woocommerce

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();
Run Code Online (Sandbox Code Playgroud)

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.

Loi*_*tec 5

要获得所有运输类别,您只需要以下内容:

$shipping_classes = get_terms( array('taxonomy' => 'product_shipping_class', 'hide_empty' => false ) );
Run Code Online (Sandbox Code Playgroud)

测试和工作。这将为您提供WP_Term所有运输类的对象数组。

在 Woocommerce 中,运输类属于product_shipping_class自定义分类法。


或者,您可以通过简单的 SQL 查询使用此自定义函数:

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'
    " );
}
Run Code Online (Sandbox Code Playgroud)

代码位于活动子主题(或活动主题)的 function.php 文件中。

用法(测试示例):

$shipping_classes = wc_get_shipping_classes(); // Get Shipping Classes
echo '<pre>'; print_r($shipping_classes); echo '</pre>'; // Test raw output   
Run Code Online (Sandbox Code Playgroud)