I'm attempting to use the 'woocommerce_order_shipping_to_display' filter to show 'Free' in the WooCommerce email table when no shipping charges will be incurred. In the image, I'm trying to get 'Flat Rate' to display as 'Free'. My PHP is moderate, and I can't get my code quite there. Does anyone see what I could be missing?
My function breaks the actual email so I can't see if it's working or not. When the function is in place, and I resend a processing email, instead of resending, it opens in the same browser window without anything below the main email body table data (screenshot).
/* return custom text on email when shipping is free */
add_filter( 'woocommerce_order_shipping_to_display', 'filter_email_shipping_text', 10, 2 );
function filter_email_shipping_text( $shipping, $this ) {
global $woocommerce;
if ( $this->get_shipping_method() ) {
$shipping = __( 'Free', 'woocommerce' );
}
return $shipping;
}
UPDATED
I've scavenged for a few similar cases, and I've rewritten the function below. This still doesn't work, but I think I needed to initialise the WC_Order class to tell the function which order to reference. Can anyone help me finish it off?
/* return custom text on email when shipping is free */
add_filter( 'woocommerce_order_shipping_to_display', 'filter_email_shipping_text', 10 );
function filter_email_shipping_text( $shipping ) {
global $wcdn;
$order = new WC_Order($wcdn->print->order_id);
if ( $order->get_shipping_method() || $order->order_shipping = 0 ) {
$shipping = sprintf(__( 'Free', 'woocommerce' ));
}
return $shipping;
}
CONCLUSION
I was able to fix my function and it now works how intended. This is the working function and filter in case anyone need to replicate.
/* return custom text on email when shipping is free */
add_filter( 'woocommerce_order_shipping_to_display', 'filter_email_shipping_text', 10, 2 );
function filter_email_shipping_text( $shipping, $order_id ) {
global $woocommerce, $post;
$order = new WC_Order( $order_id );
if ( $order->order_shipping == 0 ) {
$shipping = sprintf(__( 'Free!', 'woocommerce' ));
}
return $shipping;
}