I have a custom shipping method and I want it to display its description (shipping instructions) on Thank you page and in email sent to customer. Just as payment gateways do. I am hooking to woocommerce_thankyou
hook in my shipping method init()
function. It works, but … it works like eight times. Those hooked functions are firing multiple times. My shipping method looks like this:
<?php
class WC_Shipping_XY extends WC_Shipping_Method {
function __construct( $instance_id = 0 ) {
$this->id = 'my-shipping';
// etc etc
$this->init();
}
function init() {
$this->init_form_fields();
// etc
add_action( 'woocommerce_thankyou', array( $this, 'woocommerce_thankyou' ), 5, 1 );
}
function woocommerce_thankyou( $order_id ) {
$order = wc_get_order( $order_id );
if( $order->has_shipping_method('my-shipping') ) {
echo wpautop( wptexturize( $this->description ) );
}
}
}
Shipping method description is duplicated many times on Thank you page. I don’t know why. Is shipping method constructor called more than once? (Obviously it is …)
2
Answers
Well, I finally found out this behaviour is "by design", someone asked the same question on WooCommerce Github (issue).
Shipping methods/instances are not singletons and can be init/loaded/constructed multiple times depending on whats going on.
It's not possible to hook any function inside shipping method class - if so, it will result in multiple function calls. Period.
I think this is how it should be done.
Please see that it has a
description
class variable inside of it, which is different frommethod_description
used by WooCommerce.I have tested this code and it works.
Screenshot below. You can see
Some other description
on the thank you page.