WC_Site_Tracking::add_enable_tracking_function()public staticWC 1.0

Adds a function to load tracking scripts and enable them client-side on the fly. Note that this function does not update woocommerce_allow_tracking in the database and will not persist enabled tracking across page loads.

Method of the class: WC_Site_Tracking{}

No Hooks.

Return

null. Nothing (null).

Usage

$result = WC_Site_Tracking::add_enable_tracking_function();

WC_Site_Tracking::add_enable_tracking_function() code WC 8.6.1

<?php
public static function add_enable_tracking_function() {
	global $wp_scripts;

	if ( ! isset( $wp_scripts->registered['woo-tracks'] ) ) {
		return;
	}

	$woo_tracks_script = $wp_scripts->registered['woo-tracks']->src;

	?>
	<script type="text/javascript">
		window.wcTracks.enable = function( callback ) {
			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
}