Skip to content

Instantly share code, notes, and snippets.

@patrickposner
Created February 5, 2024 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patrickposner/ec91624067a9f69d259da251c33e83a0 to your computer and use it in GitHub Desktop.
Save patrickposner/ec91624067a9f69d259da251c33e83a0 to your computer and use it in GitHub Desktop.
Klar Tracking in WooCommerce
<?php
// Klar:sendOrderEvent
add_action( 'woocommerce_thankyou', function ( $order_id ) {
?>
<script>
(function () {
window._k_q = window._k_q || [];
window._k_q.push(["Klar:sendOrderEvent", {
orderId: <?php echo esc_html( $order_id ); ?>,
}]);
})();
</script>
<?php
} );
// Klar:sendUpdateCheckoutEvent
add_action( 'wp_footer', function () {
global $wp;
// Is it the checkout page and the checkout is not completed?
if ( is_checkout() && empty( $wp->query_vars['order-pay'] ) && ! isset( $wp->query_vars['order-received'] ) ) {
// We don't have the cartId, checkoutId, so we just send the customer ID instead.
$customer_id = get_current_user_id(); // Defaults to 0 if not logged in
?>
<script>
(function () {
window._k_q = window._k_q || [];
window._k_q.push(["Klar:sendUpdateCheckoutEvent", {
cartId: <?php echo esc_html( $customer_id ); ?>,
checkoutId: <?php echo esc_html( $customer_id ); ?>,
customerId: <?php echo esc_html( $customer_id ); ?>
}]);
})();
</script>
<?php
}
} );
// Klar:sendUpdateCartEvent
add_action( 'wp_footer', function () {
// We don't have the cartId, checkoutId, so we just send the customer ID instead.
$customer_id = get_current_user_id(); // Defaults to 0 if not logged in
?>
<script>
jQuery(document).on('click', '.woocommerce-cart-form :button[type=submit]', function() {
window._k_q = window._k_q || [];
window._k_q.push(["Klar:sendUpdateCartEvent", {
cartId: <?php echo esc_html( $customer_id ); ?>,
}]);
});
jQuery(document).on('change', '.woocommerce-cart-form :input[type=number]', function() {
window._k_q = window._k_q || [];
window._k_q.push(["Klar:sendUpdateCartEvent", {
cartId: <?php echo esc_html( $customer_id ); ?>,
}]);
});
</script>
<?php
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment