如何让WordPress主题特定页面的SweetAlert弹窗仅显示一次?
Hey there! To get that SweetAlert to pop up only once for each user (and never again on their subsequent visits), we can leverage the browser's localStorage API—it lets us store small pieces of data persistently across browser sessions. Here's how to tweak your existing code:
Modified Code
jQuery(document).ready(function($) { // Check if we're on a single post page AND the user hasn't seen the alert before if ($('body').hasClass('post-template-default') && !localStorage.getItem('hasSeenSwipeAlert')) { if (screen.width <= 991) { setTimeout(function(){ swal({ type: 'info', title: 'You can swipe!', text: 'Swipe to Right or Left to navigate through posts.', showConfirmButton: false // Fixed the string-to-boolean issue here }); // Mark the alert as seen in localStorage localStorage.setItem('hasSeenSwipeAlert', 'true'); }, 1000); } } });
How It Works
- LocalStorage Check: We first verify if
localStorage.getItem('hasSeenSwipeAlert')returnsnull—this means the user hasn't encountered the alert yet. - Trigger Popup Only Once: If the check passes, we show the alert as before, then immediately store a flag (
hasSeenSwipeAlert: 'true') in localStorage. - Persistent Storage: This flag stays in the user's browser until they clear their local storage or you manually remove it.
Testing Tips
If you need to test the popup again (to confirm it only shows once), open your browser's developer tools (F12), go to the Application tab, find Local Storage under Storage, and delete the hasSeenSwipeAlert entry. Alternatively, run this in the console:
localStorage.removeItem('hasSeenSwipeAlert');
Note
Keep in mind that if a user clears their browser cache/data, the flag will be removed, and the popup will show again on their next visit—this is standard behavior for client-side storage.
内容的提问来源于stack exchange,提问作者bluemask11

