For my Fancy Product Designer plugin I need to get the order ID in the order-received page and view-order page. Woocommerce offers a filter hook to get the ordered item link: woocommerce_order_item_name
, which is currently not documented in the filter hooks reference. I found it when I browsed through the woocommerce source code. Its located in the order-details.php template. For older version than 2.1 it was woocommerce_order_table_product_title.
Via this filter hook you can change the item link and receive an array that represents the item. The array contains following values:
$reserved_item_meta_keys = array(
'name',
'type',
'item_meta',
'qty',
'tax_class',
'product_id',
'variation_id',
'line_subtotal',
'line_total',
'line_tax',
'line_subtotal_tax'
);
Let’s see how it looks like when using the filter hook:
add_filter( 'woocommerce_order_item_name', 'add_edit_link_to_order_item' , 10, 2 );
function add_edit_link_to_order_item( $link, $item ) {
return $link;
}
For my Fancy Product Designer plugin I need to get the current order ID, in older version it was very easy, because it was appended as GET parameter in the URL, so I could receive it via a simple $_GET request. It’s still available as GET parameter, when default permalinks are used. But for custom permalinks, it’s now shown as path in the URL, e.g. my-account/view-order/398/
. I was browsing through the source code of woocommerce and was not thinking that it will be such a tough task to get the order ID, actually I thought woocommerce offers a simple solution to get the order ID of an item, but I could not find any simple solution, so I created this little dirty snippet:
add_filter( 'woocommerce_order_item_name', 'add_edit_link_to_order_item' , 10, 2 );
function add_edit_link_to_order_item( $link, $item ) {
//check if on view-order page and get parameter is available
if(isset($_GET['view-order'])) {
$order_id = $_GET['view-order'];
}
//check if on view order-received page and get parameter is available
else if(isset($_GET['order-received'])) {
$order_id = $_GET['order-received'];
}
//no more get parameters in the url
else {
$url = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
$template_name = strpos($url,'/order-received/') === false ? '/view-order/' : '/order-received/';
if (strpos($url,$template_name) !== false) {
$start = strpos($url,$template_name);
$first_part = substr($url, $start+strlen($template_name));
$order_id = substr($first_part, 0, strpos($first_part, '/'));
}
}
//yes, I can retrieve the order via the order id
$order = new WC_Order($order_id);
return $link;
}
First of all…if anyone has a simpler solution, please let me know via the comments.