WC_Tracks::record_event
Record an event in Tracks - this is the preferred way to record events from PHP. Note: the event request won't be made if $properties has a member called error.
Array values in event properties are automatically converted to prevent invalid property names:
- Indexed arrays (e.g., ['a',
'b', 'c']) become comma-separated strings:'a,b,c' - Associative arrays (e.g., ['key' => 'val']) become JSON strings:
'{"key":"val"}' - Empty arrays become empty strings
Examples:
// Indexed array - becomes comma-separated string WC_Tracks::record_event( 'checkout_viewed', array( 'blocks' => array( 'woocommerce/cart-items', 'woocommerce/checkout-totals' ) ) ); // Results in: blocks=woocommerce%2Fcart-items%2Cwoocommerce%2Fcheckout-totals
// Associative array - becomes JSON string WC_Tracks::record_event( 'settings_changed', array( 'options' => array( 'enabled' => true, 'count' => 5 ) ) ); // Results in: options=%7B%22enabled%22%3Atrue%2C%22count%22%3A5%7D
For complex structures, consider explicitly JSON-encoding before passing to record_event().
Method of the class: WC_Tracks{}
No Hooks.
Returns
true|false|WP_Error. True for success or WP_Error if the event pixel could not be fired.
Usage
$result = WC_Tracks::record_event( $event_name, $event_properties );
- $event_name(string) (required)
- The name of the event.
- $event_properties(array)
- Custom properties to send with the event.
Default:array()
WC_Tracks::record_event() WC Tracks::record event code WC 10.5.0
public static function record_event( $event_name, $event_properties = array() ) {
/**
* Don't track users who don't have tracking enabled.
*/
if ( ! WC_Site_Tracking::is_tracking_enabled() ) {
return false;
}
$user = wp_get_current_user();
// We don't want to track user events during unit tests/CI runs.
if ( $user instanceof WP_User && 'wptests_capabilities' === $user->cap_key ) {
return false;
}
$prefixed_event_name = self::PREFIX . $event_name;
$properties = self::get_properties( $prefixed_event_name, $event_properties );
$event_obj = new WC_Tracks_Event( $properties );
if ( is_wp_error( $event_obj->error ) ) {
return $event_obj->error;
}
return $event_obj->record();
}