Using a WordPress plugin suite called Toolslet, I’ve been building a content template to dynamically display Woocommerce order information.
I’ve written a shortcode that works perfectly outside of Guttenberg to display the order information for the current order in the loop:
/*** Shortcode to return any aspect of a Woocommerce order ***/
/* Accepts parameters 'id' and 'token':
/* 'id' = If ID is blank current loop item ID is used otherwise it needs to be a class ID
/* 'attribute' = The Woocommerce order array item wanted. Defaults to order ID */
function get_order_info($atts) {
//Set the default $atts values
defaults = array(
'id' => get_the_ID(),
'attribute' => 'id'
);
//Apply default atts if none have been set
$atts = shortcode_atts( $defaults, $atts );
//Get the WC_Order object for the current order in the loop
$order = wc_get_order( $atts['id'] );
//Get the order data
$order_data = $order->get_data();
//Return whichever order data item is requested
return $order_data[$atts['attribute']];
}
add_shortcode("order_info", "get_order_info");
But trying to use this in a content template (a post that is reused to display information for any post in a custom post type) causes Guttenberg to display:
Updating failed. The response is not a valid JSON response.
And PHP throws this error:
Call to a member function get_data on bool
Both of these errors are the result of this line of code:
$order_data = $order->get_data();
As I understand it, the PHP error is saying that get_data() is returning a boolean, ie FALSE, which means that it’s not getting the order ID correctly. However is saving and getting the order ID because working on the front end and trying to dump and of the following displays the correct ID:
$defaults['id'];
$atts['id'];
get_the_ID();
I’ve seen similar questions on here, but they all focus on the ID not being present when it clearly is here.