2
votes

I would like to display variable products shipping class set for each variant. I realize that I may need to have a mix of php and Javascript but I would like to get the PHP side right first.

I am guessing the best way to start is to use:

if( $product->is_type( 'simple' ) ) {
    $product = wc_get_product();

    $shipping_class = $product->get_shipping_class();
} elseif( $product->is_type( 'variable' ) ) {
    $product = wc_get_product();
    $shipping_class = $product->get_shipping_class();
}

But I am not sure how to get the product variant shipping class or if I am doing this correctly. Looking into wc_get_product_variation or variation to see if it has the answer.

Any help would be appreciated possibly display all as an array and use javascript to hide the selected.

How do I get the variant shipping class?

enter image description here

1

1 Answers

1
votes

To get the variations shipping classes of a defined variable product Id, two ways:

1) Using wp_get_post_terms() function for product_shipping_class taxonomy:

// Get the WC_Product_Variable instance Object (if needed)
$product = wc_get_product( $product_id );

// Initializing
$shipping_classes = array();

// Loop through the visible variations IDs 
foreach ( $product->get_visible_children() as $variation_id ) {
    // Get the variation shipping class WP_Term object
    $term = wp_get_post_terms( $variation_id, 'product_shipping_class' ); 

    if( empty($term) ) {
        // Get the parent product shipping class WP_Term object
        $term = wp_get_post_terms( $product->get_id(), 'product_shipping_class' ); 

        // Set the shipping class slug in an indexed array
        $shipping_classes[$variation_id] = $term->slug;
    }
}

// Raw output (for testing)
var_dump($shipping_classes);

This will give you an array of variation Id / shipping class pairs.


2) Using get_shipping_class_id() WC_Product method:

// Get the WC_Product_Variable instance Object (if needed)
$product = wc_get_product( $product_id );

// Initializing
$shipping_classes = array();

// Loop through the visible variations IDs 
foreach ( $product->get_visible_children() as $variation_id ) {
    // Get the Product Variation instance Object
    $variation = wc_get_product($variation_id); 

    // Get the shipping class ID
    $term_id = $variation->get_shipping_class_id(); 

    // The shipping class WP_Term Object
    $term = get_term_by('term_id', $term_id, 'product_shipping_class'); 

    // Set the shipping class slug in an indexed array
    $shipping_classes[$variation_id] = $term->slug;
}

// Raw output (for testing)
var_dump($shipping_classes);