settings = $settings; $this->recorder = $recorder; } /** * Register hooks. * * @return void */ public function boot(): void { if ( ! $this->settings->load()->flag( 'track_users' ) ) { return; } add_action( 'user_register', array( $this, 'on_register' ), 20, 1 ); add_action( 'wp_login', array( $this, 'on_login' ), 20, 2 ); } /** * A new account was created. * * @param int $user_id New user id. * @return void */ public function on_register( $user_id ): void { $user = get_userdata( (int) $user_id ); if ( ! $user instanceof WP_User ) { return; } $identity = $this->identity_for( $user ); $this->recorder->identify( $identity ); $this->recorder->record( Event::create( 'sign_up', Event::stable_id( 'sign_up', (string) $user->ID ) ) ->with_identity( $identity ) ->with_properties( array( 'method' => 'wordpress' ) ) ->at( time() ) ); } /** * Somebody signed in. * * @param string $user_login Username. * @param WP_User|null $user The user. * @return void */ public function on_login( $user_login, $user = null ): void { unset( $user_login ); if ( ! $user instanceof WP_User ) { return; } $identity = $this->identity_for( $user ); // Identify rather than an event. A login is not a conversion, but it is the best chance to // re-link this browser to a known person — a returning customer on a new device is otherwise a // second anonymous visitor until they buy something. $this->recorder->identify( $identity ); } /** * Build the identity for a user. * * @param WP_User $user The user. * @return Identity */ private function identity_for( WP_User $user ): Identity { $traits = array( 'name' => $user->display_name, ); $role = is_array( $user->roles ) ? reset( $user->roles ) : ''; if ( is_string( $role ) && '' !== $role ) { $traits['role'] = $role; } /** * Filters the traits sent with a WordPress user. * * Anything added here is stored against the person's AdPix profile, so it should be an attribute * the site owner has a reason to segment on rather than everything the site happens to know. * * @since 1.0.0 * * @param array $traits Profile attributes. * @param WP_User $user The user. */ $traits = (array) apply_filters( 'adpix_analytics_user_traits', $traits, $user ); return Identity::from( array( // The WordPress user id, not the email: it never changes, so a customer who updates their // address stays the same person rather than becoming a second profile. 'external_id' => (string) $user->ID, 'email' => $user->user_email, 'phone' => (string) get_user_meta( $user->ID, 'billing_phone', true ), 'traits' => $traits, ) ); } }