Home > Software engineering >  Show shipping class on product page (variable products) Woocommerce
Show shipping class on product page (variable products) Woocommerce

Time:12-09

I'm struggling to show the different shipping classes on the product page in Woocommerce. I have found several codes that show the shipping class of simple products. But not codes that show the classes of the different variations on a variable product.

The code should get the shipping class of simple products to show (cause I gave several simple products). But when the product is a variable product it needs to show the shipping classes of the variations instead of the parent shipping class.

I am not capable of coding this, hoping there is someone who is skilled enough and willing to help.

It would be nice if the front end looks like this: Front end shipping class

CodePudding user response:

One way is to use the variation stock filter woocommerce_get_stock_html() which takes 2 arguments:

  • $html for displaying the content
  • $product Product object

You need to set the shipping class to each variation and add this to your functions.php:

/**
 * Add shipping class for Product variations.
 *
 * @param  mixed      $html    Displays stock html content. 
 * @param  WC_Product $product Product Object.
 * 
 * @return mixed      $html    Updated stock html content.
 */
add_filter( 'woocommerce_get_stock_html', 'amp_woocommerce_get_stock_html', 10, 2 );

function amp_woocommerce_get_stock_html( $html, $product ) {
   
   $shipping_class = $product->get_shipping_class();

   if ( ! empty( $shipping_class ) ) {
      $html .= sprintf( '<p ><strong>%s</strong> %s</p>', __( 'Shipping:', 'text-domain' ), $shipping_class );
   }
   
   return $html;
}
  • Related