Discuss and resolve questions on Liquid, JavaScript, themes, sales channels, and site speed enhancements.
I've been working on optimizing my Google Ads campaigns, and I've set up a URL parameter that adds the keyword to the URL when someone clicks on my ad. Now, I'm exploring ways to dynamically update my product headlines based on this keyword.
I've come up with a JavaScript solution to append the keyword to the product headline on my product pages. I'd like to share the script and get your thoughts on whether this approach would work well within the Shopify environment.
The script below is chat gpt generated and it's just an example of what i'm trying to get to work. I think im nearly there. These are the code's rules I need:
1. My URL parameter is this: {lpurl}&utm_content={keyword}, so when someone clicks my add the keyword they searched for will be in the end of the URl.
2. Then I need the code to say: IF there is a keyword mentioned like that at the end of the url ADD it to the end of my headline of the product. So basicly need a script that injects it like this and that its universal and applies on all products. Anyone can help me?
<script>
// Function to get URL parameter by name
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
const regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
const results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
// Get the 'keyword' parameter from the URL
const keywordParam = getUrlParameter('keyword');
// Check if 'keyword' parameter exists and update the headline
if (keywordParam) {
document.addEventListener('DOMContentLoaded', function () {
// Update the product headline with the keyword
const productHeadline = document.querySelector('.product__title h2');
if (productHeadline) {
productHeadline.innerText += ` | ${keywordParam}`;
}
});
}
</script>
Ig it needs to be something like this but where do I put the code so it's for all product pages?
<script>
document.addEventListener('DOMContentLoaded', function() {
const urlParams = new URLSearchParams(window.location.search);
const keyword = urlParams.get('utm_content');
if (keyword) {
const productTitle = document.querySelector('.product__title h2.h1');
if (productTitle) {
productTitle.innerText += ` | ${keyword}`;
}
}
});
</script>
Im testing it now by adding the example "snicker" at the end of my url : ...?utm_content=snicker
As 2024 wraps up, the dropshipping landscape is already shifting towards 2025's trends....
By JasonH Nov 27, 2024Hey Community! It’s time to share some appreciation and celebrate what we have accomplis...
By JasonH Nov 14, 2024In today’s interview, we sat down with @BSS-Commerce to discuss practical strategies f...
By JasonH Nov 13, 2024