John Davidson

javascript - Passing UTM Parameters Across WP Link (Working with bugs need advice)

0 comments
Message:


This code DOES work, however I can't make it stop adding blank UTM to the other links.


The way it should work is if there are no UTM strings set it does nothing. This snippet passes the UTM data onto other links across the site so we can use UTM paramaters across the site to trigger show/hide content.


<?php $utm_source = isset($_GET['utm_source']) ? $_GET['utm_source'] : ""; ?>
<?php $utm_medium = isset($_GET['utm_medium']) ? $_GET['utm_medium'] : ""; ?>
<?php $utm_campaign = isset($_GET['utm_campaign']) ? $_GET['utm_campaign'] : ""; ?>
<?php $utm_term = isset($_GET['utm_term']) ? $_GET['utm_term'] : ""; ?>
<?php $utm_content = isset($_GET['utm_content']) ? $_GET['utm_content'] : ""; ?>

<script type="text/javascript">
jQuery(document).ready(function ($) {
$(function() {
$("a").attr('href', function(i, h) {
return h + (h.indexOf('?') != -1 ? "&utm_source=<?php echo $utm_source; ?>&utm_medium=<?php echo $utm_medium; ?>&utm_campaign=<?php echo $utm_campaign; ?>&utm_term=<?php echo $utm_term; ?>&utm_content=<?php echo $utm_content; ?>" : "?utm_source=<?php echo $utm_source; ?>&utm_medium=<?php echo $utm_medium; ?>&utm_campaign=<?php echo $utm_campaign; ?>&utm_term=<?php echo $utm_term; ?>&utm_content=<?php echo $utm_content; ?>");
});
});
});
</script>


My Answer:
To prevent the code from adding blank UTM parameters to other links, you can add a condition to check if the UTM parameters are not empty before adding them to the other links. Here's an updated version of the code with this condition:

javascript
// Get UTM parameters from current URL
const urlParams = new URLSearchParams(window.location.search);
const utmSource = urlParams.get('utm_source');
const utmMedium = urlParams.get('utm_medium');
const utmCampaign = urlParams.get('utm_campaign');

// Check if UTM parameters are not empty
if (utmSource && utmMedium && utmCampaign) {
// Add UTM parameters to all links on the page
document.querySelectorAll('a').forEach(link => {
const href = new URL(link.href);
href.searchParams.set('utm_source', utmSource);
href.searchParams.set('utm_medium', utmMedium);
href.searchParams.set('utm_campaign', utmCampaign);
link.href = href.toString();
});
}


This code will only add the UTM parameters to other links if all three UTM parameters (`utm_source`, `utm_medium`, `utm_campaign`) are present in the current URL. If any of the UTM parameters are missing or empty, it will not add them to the other links.

Rate this post

4 of 5 based on 7078 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us