'Add custom shortcode to Wordpress / WooCommerce

I try to add a custom shortcode to my system. But its not working as it should. When I try to use that new created shortcode in a block element [testshortcode] i get a fatal error. What i'm doing wrong? :(

function dokan_thank_you_order_received_text_modified( $thank_you_title, $order ) {
    return __( '<br><h2>'.'Hallo ', 'woocommerce' ) . $order->get_billing_first_name() . __( ', danke für deine Bestellung!'.'</h2><br>', 'woocommerce' );
}

add_shortcode('testshortcode', 'dokan_thank_you_order_received_text_modified');


Solution 1:[1]

As commenter disinfor stated, you haven't provided an order for the shortcode function to use. So, you're probably getting an error for trying to use a method ( get_billing_first_name() ) on a non-existent object ( $order ).

It looks like you're trying to modify the thank you text from the thankyou.php template, in which case you'd probably want to use the woocommerce_thankyou_order_received_text filter.

That would look more like this:

add_filter( 'woocommerce_thankyou_order_received_text', 'dokan_thank_you_order_received_text_modified', 10, 2 ) ;

function dokan_thank_you_order_received_text_modified( $text, $order ) {

    return __( '<br><h2>'.'Hallo ', 'woocommerce' ) . $order->get_billing_first_name() . __( ', danke für deine Bestellung!'.'</h2><br>', 'woocommerce' );

}

If, however, you need to add a shortcode to a block element as you stated, then you'll need to get the order object from available data. That may vary with context and implementation, so I think you'd have to provide more information.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1