I have about 60 landing pages that use different phone numbers on them. I am using a combination of WordPress and Advanced Custom Fields to place the phone numbers on their respective pages.
I am being asked to show a <div>
based on the landing page URL that will not only show the phone number assigned to that page, but, keep showing the <div>
(and phone number) regardless of what page the user navigates to on the website.
I have found little to no support on how to make the <div>
remain visible throughout the entire session until the user closes the window.
I am thinking that this will somehow revolve around a cookie and Dynamic Number Insertion but I have no real progress to speak of. Should this be done using PHP or JS? Does a plugin exist that would allow for this on WordPress? I’m open to all suggestions.
Advertisement
Answer
Please try this code. Like @John C mentioned, WP Engine doesn’t recommend Cookie nor PHP Session for the sake of performance and security. This is pure JavaScript code, and I think this will solve your problem.
Code in your Post/Page template file:
<div id="phone-number"></div> <?php if( get_field('phone_number') ): ?> <script type="text/javascript"> let phone_number = "<?php the_field('phone_number'); ?>"; </script> <?php endif; ?>
Code in your theme JavaScript file:
<script type="text/javascript"> // in the case of the div data is persistent on the same site // let storage = localStorage; // in the case of the div data is persistent in the same tab, but not in new tab let storage = sessionStorage; let key = "phone_number"; // storage key var global_phone_number = storage.getItem(key); // check if storage data is set before if (null === global_phone_number) { // if not set the data on page into storage global_phone_number = phone_number ? phone_number : ''; storage.setItem(key, global_phone_number); } document.getElementById('phone-number').innerHTML = global_phone_number; </script>