Skip to content

Snippet: Trigger Lighbox via URL

In order for this code to work you first need to insert a theme button element that is set to trigger your lighbox and give it a unique ID. Now you can trigger the lightbox using the URL format: mysite.com/?open=my_lighbox_item_id

Now, in this example we are using the "open" parameter to trigger the lightbox. You may want to consider using a different word such as "modal, popup...etc" Just change the word "open" in the code below to whatever you want and then use that in your URL. This may be needed if you are using another plugin that is already using that word for something else.

Last, if you want to have the lightbox open when accessing the page but not have any visible element (button) on the page, simply use the visibility settings to hide the button, the code will still work.

// Trigger lightbox based on URL using the format: mysite.com/?open=my_lighbox_item_id
add_action( 'wp_footer', function() { ?>

    
    var myHashLightbox = function() {
        let queryString = window.location.search;
        let urlParams = new URLSearchParams( queryString );
        let modalID = urlParams.get( 'open' );
        let modal = document.querySelector( '#' + modalID );
        if ( modal && modal.classList.contains( 'wpex-lightbox' ) ) {
            modal.click();
        }
    };
    window.addEventListener( 'load', myHashLightbox );
    

<?php } );
All PHP snippets should be added via child theme's functions.php file or via a plugin. We recommend Code Snippets (100% Free) or WPCode (sponsored)
Back To Top