WC_Site_Tracking::add_enable_tracking_function()

Adds a function to load tracking scripts and enable them client-side on the fly.


Description Description

Note that this function does not update woocommerce_allow_tracking in the database and will not persist enabled tracking across page loads.


Source Source

File: includes/tracks/class-wc-site-tracking.php

	public static function add_enable_tracking_function() {
		global $wp_scripts;
		$woo_tracks_script = $wp_scripts->registered['woo-tracks']->src;

		?>
		<script type="text/javascript">
			window.wcTracks.enable = function( callback = null ) {
				window.wcTracks.isEnabled = true;

				var scriptUrl = '<?php echo esc_url( $woo_tracks_script ); ?>';
				var existingScript = document.querySelector( `script[src="${ scriptUrl }"]` );
				if ( existingScript ) {
					return;
				}

				var script = document.createElement('script');
				script.src = scriptUrl;
				document.body.append(script);

				// Callback after scripts have loaded.
				script.onload = function() {
					if ( 'function' === typeof callback ) {
						callback( true );
					}
				}

				// Callback triggered if the script fails to load.
				script.onerror = function() {
					if ( 'function' === typeof callback ) {
						callback( false );
					}
				}
			}
		</script>
		<?php
	}

Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.