Checkout | Schedule Orders: Attach Affiliate Metadata at Checkout for Future Scheduled Order Processing
In this example, a developer uses the autoship_create_scheduled_order_data filter to capture affiliate data at checkout to add to the created Scheduled Order's metadata.
Then they hook into the woocommerce_payment_complete action to add an order note identifying the subsequent orders created from Scheduled Order processing, were attributed to the affiliate's original checkout order
Remember: Always test new code on a staging site before adding it to your live site.
Code Example:
**
* Add Order Attribution to an Autoship Order's Metadata for future use in processed orders.
* Example is each WC Checkout Order has an affiliate id which should carry on to all
* Scheduled Orders spawned from that Checkout Order.
*
* @param array $scheduled_order_data The Scheduled Order data to be sent to QPilot
* @param int $order_id The WC Order ID
* @return array The filtered Scheduled Order Data
*/
function xx_add_inherited_metadata_to_scheduled_orders( $scheduled_order_data, $order_id ){
// Retrieve the Affiliate ID from the WC Order and Attach it to the Scheduled Order data.
$affliate_id = get_post_meta( $order_id, '_affiliate_id', NULL );
// If there is an associated affiliate id then get the current orders metadata
// add the affiliate id to that data and re-attach to the scheduled order data array
if ( isset( $affliate_id ) ){
$metadata = isset( $scheduled_order_data['metadata'] ) ? $scheduled_order_data['metadata'] : array();
$metadata['wc_affiliate_id'] = $affliate_id;
$scheduled_order_data['metadata'] = $metadata;
}
return $scheduled_order_data;
}
add_filter( 'autoship_create_scheduled_order_data', 'xx_add_inherited_metadata_to_scheduled_orders', 10, 2 );
/**
* Adds An Order Note based on Attribution passed through from the Original Checkout Order.
*
* @param int $order_id The WC Order ID
*/
function xx_add_note_based_on_inherited_metadata( $order_id ){
// Retrieve the WC Order
$order = wc_get_order( $order_id );
if ( !$order )
return;
// Retrieve the QPilot Metadata & The Partner Info if it exists
$qpilot_metadata = get_post_meta( $order->get_id(), '_qpilot_scheduled_order_metadata', true );
$wc_affiliate_id = isset( $qpilot_metadata['wc_affiliate_id'] ) ? $qpilot_metadata['wc_affiliate_id'] : '';
// If there is an associated partner id & name so add a note to the order.
if ( !empty( $wc_affiliate_id ))
$order->add_order_note( sprintf( 'This order originated from affiliate %s checkout order.', $wc_affiliate_id ) );
}
add_action( 'woocommerce_payment_complete', 'xx_add_note_based_on_inherited_metadata', 10, 1 );