How to add a cookie compliance banner to your Shopify theme manually
You can add a cookie compliance banner to your theme to allow customers to consent to track of non-essential cookies. This allows customers to consent to relevant, region-specific, tracking laws such as GDPR and CCPA.
Following the below steps to adding this to your Shopify theme:
- From your Shopify admin, go to Online Store > Themes.
- Click Actions, and then click Edit Code.
- Under the Snippets folder, click on Add a new snippet link to create a new snippet
- Fill the snippet name – cookie-banner to the field on the dialog and click Create snippet button.
- In the online code editor, please paste the below code1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768<style>#cookies-banner {display: none;justify-content: center;align-items: center;padding: 1em;position: fixed;bottom: 0px;width: 100%;background: #fff;border-top: 1px solid #dcdcdc;}</style><div id="cookies-banner"><span>This website uses cookies to ensure you get the best experience on our website.</span><button style="margin-left: 1em;" onclick="handleDecline()">Decline</button><button style="margin-left: 1em;" onclick="handleAccept()">Accept</button></div><script>function getBannerEl() {return document.getElementById('cookies-banner');}function hideBanner(res) {getBannerEl().style.display = 'none';}function showBanner() {getBannerEl().style.display = 'block';}function handleAccept(e) {window.Shopify.customerPrivacy.setTrackingConsent(true, hideBanner);document.addEventListener('trackingConsentAccepted',function() {console.log('trackingConsentAccepted event fired');});}function handleDecline() {window.Shopify.customerPrivacy.setTrackingConsent(false,hideBanner);}function initCookieBanner() {const userCanBeTracked = window.Shopify.customerPrivacy.userCanBeTracked();const userTrackingConsent = window.Shopify.customerPrivacy.getTrackingConsent();if(!userCanBeTracked && userTrackingConsent === 'no_interaction') {showBanner();}}window.Shopify.loadFeatures([{name: 'consent-tracking-api',version: '0.1',}],function(error) {if (error) {throw error;}initCookieBanner();});</script>
- Click Save.
Step 2: Include the snippet
- Under the Layout folder, click onto theme.liquid to open the file editor.
- In the online code editor, scroll down the page until you find the close body tag.
- Paste the below code just before the tag1{% render 'cookie-banner' %}
- Click Save and you are done.
The functionality of the banner in the guide above provides customers with the option to “accept” or “decline” cookie tracking, hides the banner once a selection has been made, and saves the selection to prevent the banner from being shown in the future. This selection is saved for 365 days, or until the customer clears their cookies.
Happy coding!