Skip to content

Instantly share code, notes, and snippets.

@marklchaves
Last active June 14, 2023 05:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marklchaves/0ed10622b7d7dedc7596c373f10ab7e6 to your computer and use it in GitHub Desktop.
Save marklchaves/0ed10622b7d7dedc7596c373f10ab7e6 to your computer and use it in GitHub Desktop.
Show a popup on every third page
<?php // Ignore this first line when copying to your child theme's functions.php file.
function every_third_page() { ?>
<script type="text/javascript">
/** Set up a page counter in the browser's session storage. */
(function(){
let pc = parseInt(sessionStorage.getItem("my-page-count"));
if (!pc) {
sessionStorage.setItem("my-page-count", 1);
} else {
sessionStorage.setItem("my-page-count", pc += 1);
}
})();
// Make sure the function (IIFE) above runs before the following jQuery.
jQuery(document).ready(function ($) {
// Display a popup on every "third" page. Change 2178 throughout to your popup's HTML ID.
$("#pum-2178").on("pumBeforeOpen", function (e) { // Add a listener.
let pc = parseInt(sessionStorage.getItem("my-page-count"));
// You can change 3 to what you want. E.g., 2 opens on ever second page, 4 opens on every fourth page.
if ( (pc % 3) == 0 ) return; // If we're on a "third" page, just return so the popup displays.
PUM.preventOpen(2178); // Stop the popup from opening because we're not on a "third" page.
}); // Listener
}); // jQuery
</script>
<?php }
add_action( 'wp_footer', 'every_third_page', 500 );
/**
* You can add the PHP code snippet to your child theme's functions.php file
* or with third-party plugins such as My Custom Functions and Code Snippets.
*
* Learn more:
* - https://docs.wppopupmaker.com/article/84-getting-started-with-custom-js
* - https://docs.wppopupmaker.com/article/552-getting-started-with-custom-php
* - https://docs.wppopupmaker.com/article/409-find-the-popup-id
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment