WooCommerce PHP: Shipment Tracking Code Snippet - API addon
add_action( 'rest_api_init', 'cwpai_register_tracking_endpoint' );
function cwpai_register_tracking_endpoint() {
register_rest_route( 'cwpai/v1', '/tracking/', array(
'methods' => 'POST',
'callback' => 'cwpai_tracking_endpoint_callback',
'args' => array(
'order_id' => array(
'required' => true,
'validate_callback' => 'cwpai_validate_order_id',
),
'_cwpai_tracking_number' => array(
'required' => true,
),
'_cwpai_carrier_name' => array(
'required' => true,
),
'order_status' => array(
'required' => true,
'validate_callback' => 'cwpai_validate_order_status',
),
),
'permission_callback' => 'cwpai_permission_callback',
) );
}
function cwpai_tracking_endpoint_callback( $request ) {
$order_id = $request['order_id'];
$order = wc_get_order( $order_id );
if ( ! $order ) {
return new WP_Error( 'cwpai_invalid_order_id', 'Invalid order ID.', array( 'status' => 400 ) );
}
$order->update_meta_data( '_cwpai_tracking_number', $request['_cwpai_tracking_number'] );
$order->update_meta_data( '_cwpai_carrier_name', $request['_cwpai_carrier_name'] );
$order->set_status( $request['order_status'] );
$order->save();
return true;
}
function cwpai_validate_order_id( $param, $request, $key ) {
return is_numeric( $param );
}
function cwpai_validate_order_status( $param, $request, $key ) {
return in_array( $param, wc_get_order_statuses() );
}
function cwpai_permission_callback( $request ) {
return current_user_can( 'manage_woocommerce' ) || current_user_can( 'manage_options' );
}
Snippet Explanation
This code creates a custom endpoint in the WordPress REST API that allows tracking information to be added to an existing WooCommerce order. The endpoint is registered using the add_action
function and the rest_api_init
hook.
The endpoint URL is /wp-json/cwpai/v1/tracking/
, and it accepts POST requests. The parameters that can be included in the request are order_id
, _cwpai_tracking_number
, _cwpai_carrier_name
, and order_status
. The order_id
is required and must be a valid order ID. The other parameters are also required, but they don't have validation callbacks.
The cwpai_tracking_endpoint_callback
function handles the request by updating the specified order with the provided tracking information. If the order ID is invalid, the function returns an error. The function updates the order meta with the tracking number and carrier name and sets the order status to the specified value. Finally, the function saves the changes to the order and returns true
.
The cwpai_validate_order_id
and cwpai_validate_order_status
functions are used to validate the order_id
and order_status
parameters, respectively. They return true
if the parameter is valid and false
otherwise.
The cwpai_permission_callback
function is used to check if the current user has permission to access the endpoint. In this case, the function checks if the user can manage WooCommerce or manage options.