Skip to content

Instantly share code, notes, and snippets.

@Juandforero9
Last active July 10, 2024 11:23
Show Gist options
  • Save Juandforero9/a5c9181a0586bad4ca61e915c4986f91 to your computer and use it in GitHub Desktop.
Save Juandforero9/a5c9181a0586bad4ca61e915c4986f91 to your computer and use it in GitHub Desktop.
Add purchase to google analytics 4 from woocommerce using measurement protocol
//add this following code to your functions template
//change values of variables on line 64 and 65
function obtenertaxonomia( $product_id, $taxonomy ) {
$terminos = wp_get_post_terms(
$product_id,
$taxonomy,
array(
'orderby' => 'parent',
'order' => 'ASC',
)
);
if ( is_array( $terminos ) && ( count( $terminos ) > 0 ) ) {
return $terminos[0]->name;
}
return '';
}
add_action( 'woocommerce_order_status_changed', 'purchasemeasurementprotocol');
function purchasemeasurementprotocol( $order_id ) {
if ( ! $order_id ) { return; }
$order = wc_get_order( $order_id );
if ($order->data['status'] == 'processing' ){
$productosarray = array();
if($order->get_coupon_codes()){
$cuopon = implode( ', ', $order->get_coupon_codes());
}else{
$cuopon = "";
}
$index=1;
foreach ( $order->get_items() as $item_id => $item ) {
if($item->get_type() == "line_item"){
$product_id = $item->get_product_id();
$variation_id = $item->get_variation_id();
$product = $item->get_product();
$product_type = $product->get_type();
$productoname = $item->get_name();
if ( 'variation' === $product_type ) {
$parent_product_id = $product->get_parent_id();
$variantproducto = implode( ',', $product->get_variation_attributes() );
$brandproducto = obtenertaxonomia($parent_product_id, 'brands');
$catproducto = obtenertaxonomia($parent_product_id, 'product_cat');
$productoname=str_replace(chr(10),'',$productoname);
$productoname=str_replace(chr(13),'',$productoname);
$productoname=str_replace("\r",'',$productoname);
$productoname=str_replace("\n",'',$productoname);
$productoname=str_replace(" - ",' ',$productoname);
}else{
$variantproducto = "";
$brandproducto = obtenertaxonomia($product_id, 'brands');
$catproducto = obtenertaxonomia($product_id, 'product_cat');
}
$producto = array(
"item_id" => strval($product->get_sku()),
"item_name" => $productoname,
"affiliation" => "",
"coupon" => "",
"currency" => $order->get_currency(),
"discount" => 0,
"index" => $index++,
"item_brand" => $brandproducto,
"item_category" => $catproducto,
"item_variant" => $variantproducto,
"item_list_id" => "measurement-protocol",
"item_list_name" => "Measurement protocol",
"price" => floatval( str_replace(",", "", $product->get_price() )),
"quantity" => floatval($item->get_quantity())
);
array_push($productosarray, $producto);
}
}
$client_id = strval(get_post_meta($order_id, '_client_idanalytics', true));
if(!$client_id || $client_id == ""){
date_default_timezone_set('America/bogota');
$ts = round( time() / 1000.0);
$rand = round( rand(9,10) * 2147483647);
$client_id = strval($rand . "." . $ts);
}
$datapedidoinicialimpia = array(
"client_id" => $client_id,
"events" => array(
array (
"name" => "purchase",
"params" => array(
"currency" => "COP",
"transaction_id" => strval($order_id),
"value" => floatval( str_replace( ",", "", $order->get_total() )),
"coupon" => $cuopon,
"shipping" => floatval(str_replace(",", "", $order->get_shipping_total())),
"tax" => floatval(str_replace(",", "", $order->get_total_tax())),
"items" => $productosarray
)
)
)
);
$measurement_id = "G-XXXXXX";
$api_secret = "XXXXXXXXXXXXXXXX";
$urlgoogle = 'https://www.google-analytics.com/mp/collect?measurement_id='.$measurement_id.'&api_secret='.$api_secret;
$datapedidocompleto = json_encode($datapedidoinicialimpia);
$logger = new WC_Logger();
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $urlgoogle,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $datapedidocompleto,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
)
));
$response = curl_exec($curl);
if($response === false){
$logger->add('measurement-analytics-custom', 'ESTRUCTURA PEDIDO: ' . $datapedidocompleto);
$error = 'ERROR ENVIAR INFORMACION A ANALYTICS PEDIDO ' . $order_id .': ' . curl_error($curl);
$logger->add('measurement-analytics-custom', $error);
}else{
$logger->add('measurement-analytics-custom', 'ESTRUCTURA PEDIDO: ' . $datapedidocompleto);
$logger->add('measurement-analytics-custom', 'CORRECTO INFORMACION A ANALYTICS PEDIDO ' . $order_id . '');
}
}
}
add_action( 'woocommerce_after_order_notes', 'my_custom_checkout_hidden_field', 10, 1 );
function my_custom_checkout_hidden_field( $checkout ) {
$measurement_id = "G-XXXXXX";
echo '<div id="user_link_hidden_checkout_field">
<input type="hidden" class="input-hidden" name="client_idanalytics" id="client_idanalytics" value="">
</div>';
echo '<script>gtag("get", "'.$measurement_id.'", "client_id", function(clientId) { document.getElementById("client_idanalytics").value = clientId; });</script>';
}
add_action('woocommerce_checkout_update_order_meta', 'customfieldactualizarmeta');
function customfieldactualizarmeta($order_id){
if ( !empty( $_POST['client_idanalytics'] ) ){
update_post_meta( $order_id, '_client_idanalytics', $_POST['client_idanalytics'] );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment