Last active
November 11, 2021 05:32
-
-
Save rdhimanam/3a3a6aee430af47f9532c02e88d2d32e to your computer and use it in GitHub Desktop.
Send SKU instead of product ID for orders
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function monsterinsights_custom_use_sku_instead_of_id( $body ) { | |
$numbers = array(); | |
foreach ( $body as $key => $value ) { | |
if ( 0 === strpos( $key, 'pr' ) ) { | |
if ( preg_match( '/\d+/', $key, $matches ) ) { | |
if ( isset( $matches[0] ) ) { | |
$numbers[] = $matches[0]; | |
} | |
} | |
} | |
} | |
$numbers = array_unique( $numbers ); | |
foreach ( $numbers as $number ) { | |
if ( isset( $body[ 'pr' . $number . 'id' ] ) ) { | |
$id = intval( $body[ 'pr' . $number . 'id' ] ); | |
$product = wc_get_product( $id ); | |
if ( $product->is_type( 'variable' ) && ! empty( $body[ 'pr' . $number . 'va' ] ) ) { | |
// It's a variation, try to use that SKU. | |
$variations = $product->get_children(); | |
if ( ! empty( $variations ) && is_array( $variations ) ) { | |
foreach ( $variations as $variation_id ) { | |
$variation = wc_get_product( $variation_id ); | |
if ( $body[ 'pr' . $number . 'va' ] === $variation->get_name() ) { | |
$sku = $variation->get_sku(); | |
} | |
} | |
} else { | |
$sku = $product->get_sku(); | |
} | |
} | |
if ( ! empty( $sku ) ) { | |
$body[ 'pr' . $number . 'id' ] = $sku; | |
} | |
} | |
} | |
return $body; | |
} | |
add_filter( 'monsterinsights_mp_api_call', 'monsterinsights_custom_use_sku_instead_of_id' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment