Discuss and resolve questions on Liquid, JavaScript, themes, sales channels, and site speed enhancements.
I'm looking to dynamically update the headings of products on my Shopify store based on a keyword extracted from a custom URL parameter. The custom URL is generated from Google Ads, and I want the script to read the keyword from a specific parameter (e.g., utm_content). I've tried the following JavaScript code, but it doesn't seem to work. Could you please review the code and provide any insights or improvements? I tried this example code:
<script>
document.addEventListener("DOMContentLoaded", function() {
// Get the current URL
var currentURL = window.location.href;
// Extract the keyword from the utm_content parameter
var keyword = getParameterByName('utm_content', currentURL);
// Update the product headings
var productHeadings = document.querySelectorAll('.product-title');
productHeadings.forEach(function(heading) {
var originalText = heading.innerText;
heading.innerText = originalText + ' {' + keyword + '}';
});
// Function to get URL parameters by name
function getParameterByName(name, url) {
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
});
</script>
Any assistance or suggestions would be greatly appreciated! Thank you.
I actually got it to work with this:
<script>
document.addEventListener('DOMContentLoaded', function() {
// Function to get UTM parameter from URL
function getUTMParameter(name) {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get(name);
}
// Get the 'utm_content' parameter from the URL
const keyword = getUTMParameter('utm_content');
// Check if the keyword is present and update the product title
if (keyword) {
const titleElement = document.querySelector('.product__title'); // Adjust the selector accordingly
if (titleElement) {
const originalTitle = titleElement.textContent;
// Check if the title hasn't been modified already
if (!originalTitle.includes(keyword)) {
// Create a new h1 element, update its content, and replace the existing title element
const newTitleElement = document.createElement('h1');
newTitleElement.textContent = originalTitle + ' - ' + keyword;
titleElement.parentNode.replaceChild(newTitleElement, titleElement);
}
}
}
});
</script>
But now it shows the title twice and then the keyword. Like this: Blue ball Blue ball keyword1
Discover how to increase customer engagement on your store with articles from Shopify A...
By Jacqui Apr 23, 2025Hey Community 👋 Did you know that March 15th is National Everything You Think Is W...
By JasonH Apr 1, 2025Discover how to increase the efficiency of commerce operations with Shopify Academy's l...
By Jacqui Mar 26, 2025