Creating a Popup in WordPress (No Plugin): Step-by-Step Guide

A popup is one of the easiest things you can build yourself in WordPress. You don’t need a plugin, a library, or a page builder. The browser already includes a popup element, and a few lines of JavaScript decide when it opens and whether the visitor has seen it before.

In this guide, you’ll build that popup step by step: the markup, the styling, the trigger, and the part most tutorials skip, remembering the visitor so the popup doesn’t open on every page.

I rebuilt this guide around the native <dialog> element. It takes care of the hard parts that hand-made div popups often get wrong: focus, the Esc key, and the dark backdrop.

Live demo: one dialog, three layouts

Layout

Content

Close it with the ×, the button, Esc, or a click on the backdrop.


    

New: the WordPress speed checklist

Thirty checks, sorted by impact. Free, no signup.

Step 1: Add the Popup Markup

The whole popup is one <dialog> element. Every major browser has supported it since March 2022. Open it as a modal, and you get three things for free:

  • A backdrop behind the popup that you can style with ::backdrop.
  • The Esc key closes it.
  • Focus moves into the popup, and the rest of the page becomes inert, so keyboard and screen reader users can’t wander behind it.

The MDN reference for the dialog element covers the full API, including the difference between show() and showModal().

Add the markup to the footer with the wp_footer hook. Put this in your child theme’s functions.php:

function my_popup_enabled() {
    // Show the popup on single posts. Change this to fit your site.
    return is_singular( 'post' );
}

function my_site_popup() {
    if ( ! my_popup_enabled() ) {
        return;
    }
    ?>
    <dialog id="site-popup" class="popup popup--center" aria-labelledby="popup-title">
        <form method="dialog">
            <button class="popup-close" aria-label="Close">&times;</button>
        </form>
        <p id="popup-title" class="popup-title">New: the WordPress speed checklist</p>
        <p>Thirty checks, sorted by impact. Free, no signup.</p>
        <a class="popup-btn" href="<?php echo esc_url( home_url( '/speed-checklist/' ) ); ?>">Read the checklist</a>
    </dialog>
    <?php
}
add_action( 'wp_footer', 'my_site_popup' );

A few details are worth noticing:

  • Any button inside <form method="dialog"> closes the popup, without a single line of JavaScript.
  • aria-labelledby gives the dialog an accessible name from its title.
  • The title is a <p>, not a heading. A heading in the footer would end up in the page outline and in table-of-contents plugins.
  • my_popup_enabled() is the one place where you decide which pages get the popup. You’ll reuse it in Step 5, so the CSS and JS only load where the markup exists.

Step 2: Style the Popup

The browser centers the modal dialog for you, with one catch explained below the code, so you mostly just style the box and backdrop. Save this as css/popup.css in your child theme:

.popup {
    box-sizing: border-box;
    width: min(420px, calc(100% - 32px));
    margin: auto;
    padding: 28px 24px 24px;
    border: 0;
    border-radius: 8px;
    background: #fff;
    color: #1d2327;
    box-shadow: 0 20px 50px rgb(0 0 0 / 0.25);
    text-align: start;
}

.popup::backdrop {
    background: rgb(0 0 0 / 0.55);
}

.popup[open] {
    animation: popup-in 0.25s ease-out;
}

@keyframes popup-in {
    from { opacity: 0; transform: translateY(12px); }
}

@media (prefers-reduced-motion: reduce) {
    .popup[open] { animation: none; }
}

.popup-close {
    position: absolute;
    top: 8px;
    inset-inline-end: 8px;
    width: 36px;
    height: 36px;
    border: 0;
    background: none;
    font-size: 22px;
    cursor: pointer;
}

.popup-title {
    margin: 0 0 8px;
    font-size: 1.25rem;
    font-weight: 700;
}

.popup-btn {
    display: inline-block;
    padding: 10px 20px;
    border: 0;
    border-radius: 4px;
    background: #2271b1;
    color: #fff;
    text-decoration: none;
    cursor: pointer;
}

Keep the margin: auto line. The browser uses automatic margins to center a modal dialog, and many themes reset every margin with * { margin: 0 }. Without that line, the popup sticks to the top-left corner. This blog’s own theme does exactly that, and I only caught it while building the demo above.

The CSS also uses logical properties like text-align: start and inset-inline-end, so the same file works on right-to-left sites without changes.

Bottom Bar and Corner Variants

A centered modal is the most intrusive layout. For announcements and notices, a bar or a small box in the corner is often a better fit. Add these classes, then swap popup--center in the markup:

.popup--bar,
.popup--corner {
    position: fixed;
    inset: auto;
    margin: 0;
}

.popup--bar {
    inset-inline: 0;
    inset-block-end: 0;
    width: 100%;
    max-width: none;
    border-radius: 0;
}

.popup--corner {
    inset-inline-end: 16px;
    inset-block-end: 16px;
    width: min(340px, calc(100% - 32px));
}

Open these two with show() rather than showModal(). That makes them non-modal: there’s no backdrop, and you can still use the page behind them.

A non-modal dialog changes two things. It doesn’t automatically sit on top of the page, which is why the CSS uses position: fixed. Esc also won’t close it, so keep a visible close button. Switch layouts in the first demo and see how it feels.

Step 3: Choose When the Popup Opens

Pick a trigger below and watch it fire inside the box:

Live demo: when should it open?
Delay 4s

Opened by:

trigger.js

    

Each trigger has a different job:

  • Delay: the simplest option. Set it too short, and it fires before the visitor has read a word.
  • Scroll depth: waits until the visitor is reading. It’s a good default for content sites.
  • Click: the visitor asks for the popup, so it never annoys anyone. Use it for “Subscribe” or “Get the coupon” buttons.
  • Exit intent: catches desktop visitors as they move to leave. It doesn’t exist on touch screens. The full version is in the guide on building an exit intent popup in WordPress.

Every snippet calls openPopup(), which you’ll write in the next step. It checks storage first, so no trigger can reopen a popup the visitor already closed.

Step 4: Remember the Visitor

Without memory, the popup opens every time the page loads. That is a quick way to annoy your readers. Store a small flag when the visitor closes it, then check that flag before you open the popup again.

You can store the flag in a cookie or in localStorage. Here is how they compare for this job:

Cookie localStorage
Sent to the server (readable in PHP) Yes No
Expires on its own Yes, with max-age No, you store a date and check it
Session-only version A cookie without max-age sessionStorage

For an “already seen it” flag, localStorage is the simpler choice. It adds no extra bytes to every request, and you do not need a library. Use a cookie only when your PHP needs to know. Before you do, read the caching section below.

Give it a try in the demo. Close the popup, reload, then jump ahead a few days. The panel under the buttons shows what your browser has stored right now.

Live demo: remember the visitor

Store the dismissal in

Show the popup

Hide for 7 days
storage.js

    

Here is the complete script with localStorage. Save it as js/popup.js in your child theme:

(function () {
    var popup = document.getElementById('site-popup');
    if (!popup) return; // no popup on this page

    var KEY = 'popup_dismissed';
    var DAYS = 7;

    function wasDismissed() {
        try {
            var t = Number(localStorage.getItem(KEY));
            if (t && Date.now() - t < DAYS * 86400000) return true;
            localStorage.removeItem(KEY);
        } catch (e) {}
        return false;
    }

    function rememberDismissal() {
        try { localStorage.setItem(KEY, Date.now()); } catch (e) {}
    }

    function openPopup() {
        if (popup.open || wasDismissed()) return;
        popup.showModal(); // use popup.show() for the bar or corner variant
    }

    // Every way of closing counts: the buttons, Esc, or a backdrop click.
    popup.addEventListener('close', rememberDismissal);

    // Close when the visitor clicks the backdrop.
    popup.addEventListener('click', function (e) {
        if (e.target !== popup) return;
        var r = popup.getBoundingClientRect();
        var inside = e.clientX >= r.left && e.clientX <= r.right &&
                     e.clientY >= r.top && e.clientY <= r.bottom;
        if (!inside) popup.close();
    });

    // Trigger: replace this line with any trigger from Step 3.
    setTimeout(openPopup, 4000);
})();

The early return on line 3 matters. It lets you limit the popup to certain pages without JavaScript errors on all the others.

The try blocks protect you if the browser blocks storage. The popup still works. It just will not remember the visitor.

The backdrop check compares the click position, since clicks on the popup’s own padding also report the dialog as their target. Chrome, Edge and Firefox support closedby="any", which does this natively, but Safari does not support it yet (November 2026). Keep the listener for now.

To test this on your own site, open your browser’s developer tools, go to Application, and delete popup_dismissed under Local storage (or Cookies). Reload, and the popup comes back.

Using a Cookie Instead

If your server needs to read the flag, swap the two storage functions for these:

function wasDismissed() {
    return document.cookie.split('; ').some(function (c) {
        return c.indexOf(KEY + '=') === 0;
    });
}

function rememberDismissal() {
    document.cookie = KEY + '=1; max-age=' + (DAYS * 86400) + '; path=/; SameSite=Lax';
}

max-age is in seconds, and path=/ makes the cookie available on every page of the site. Leave out max-age, and you get a session cookie that the browser deletes when it closes.

For more on reading and writing cookies, see JavaScript & Internet Cookies: Developers Essential Practices.

Step 5: Load the CSS and JavaScript in WordPress

Load both files the WordPress way, with wp_enqueue_scripts. Use the same my_popup_enabled() check as the markup:

function my_popup_assets() {
    if ( ! my_popup_enabled() ) {
        return;
    }
    $dir = get_stylesheet_directory_uri();

    wp_enqueue_style( 'my-popup', $dir . '/css/popup.css', array(), '1.0' );
    wp_enqueue_script( 'my-popup', $dir . '/js/popup.js', array(), '1.0', array(
        'in_footer' => true,
        'strategy'  => 'defer',
    ) );
}
add_action( 'wp_enqueue_scripts', 'my_popup_assets' );

get_stylesheet_directory_uri() points to the child theme, not the parent. The defer strategy stops the script from blocking the page while it loads.

Bump the version number ('1.0') whenever you edit either file, so browsers and caches fetch the new copy. Then check the Network tab in your browser’s developer tools to make sure both files load.

Don’t Check the Cookie in PHP on a Cached Site

It’s tempting to skip printing the popup in PHP if the visitor already has the cookie:

// Looks smart, breaks on cached sites
if ( isset( $_COOKIE['popup_dismissed'] ) ) {
    return;
}

On a site with page caching, the HTML from one visit gets saved and served to everyone. If that visitor had the cookie, nobody sees the popup. If they didn’t, everyone sees it, including people who already closed it.

This blog runs WP Rocket with Cloudflare caching pages at the edge, so I always make this decision in JavaScript. The cached HTML always contains the popup, and each browser decides for itself whether to open it.

Variations: Cookie Notice and Popup Form

The same popup can handle different jobs with a few small changes. For a WooCommerce-specific example, see how to show a message after a product is added to the cart.

A Cookie Notice Bar

The first version of this guide built a cookie notice. You can still do that with the bar variant, popup.show(), and a long DAYS value:

<dialog id="site-popup" class="popup popup--bar" aria-labelledby="popup-title">
    <p id="popup-title">We use cookies for analytics. <a href="<?php echo esc_url( get_privacy_policy_url() ); ?>">Privacy policy</a></p>
    <form method="dialog">
        <button class="popup-btn">OK</button>
    </form>
</dialog>

get_privacy_policy_url() returns the page you’ve set under Settings > Privacy, so you don’t need to hardcode a page ID.

A bar with an OK button is a notice, not consent. Under GDPR, non-essential cookies, such as analytics or ads, need an opt-in before they are set. If you set those cookies for EU visitors, use a consent tool that blocks the scripts until the visitor accepts.

The European Data Protection Board is clear about the “continue browsing” wording that many cookie bars still use:

“Actions such as scrolling or swiping through a webpage or similar user activity will not under any circumstances satisfy the requirement of a clear and affirmative action.” (EDPB Guidelines 05/2020 on consent, Example 16)

A Popup with a Form

If you want to collect emails or leads, add a form shortcode to the dialog. With Contact Form 7, copy the shortcode from the form’s edit screen:

<dialog id="site-popup" class="popup popup--center" aria-labelledby="popup-title">
    <form method="dialog">
        <button class="popup-close" aria-label="Close">&times;</button>
    </form>
    <p id="popup-title" class="popup-title">Get new posts by email</p>
    <?php echo do_shortcode( '[contact-form-7 id="abc1234" title="Popup signup"]' ); ?>
</dialog>

Then close the popup once the submit succeeds. Add this inside popup.js, where the popup variable already exists:

document.addEventListener('wpcf7mailsent', function () {
    setTimeout(function () { popup.close(); }, 2000);
});

The two-second wait gives the visitor a moment to read the success message. If you also want to send the signup to your analytics, see redirecting after a Contact Form 7 submission and sending events to analytics.

Popups, SEO and Accessibility

Google doesn’t ban popups, but Google Search Central warns about the ones that cover the content:

“Intrusive dialogs and interstitials make it hard for Google and other search engines to understand your content, which may lead to poor search performance.” (Google Search Central, Avoid intrusive interstitials and dialogs)

The same page puts it plainly: “Don’t obscure the entire page with interstitials.” On mobile, stick with the bar or corner layout, and don’t open a modal the moment the page loads.

For accessibility, the <dialog> element does most of the work. Give these a quick check before you ship:

  • Open modals with showModal(), so focus and Esc work.
  • Name the dialog with aria-labelledby.
  • Keep a visible close button with an aria-label.
  • Respect prefers-reduced-motion (the CSS in Step 2 does).
  • Don’t reopen it on every page view. Once per visitor is enough.

FAQs

Common questions about building a popup in WordPress without a plugin:

Can I show the popup only on specific pages?
Yes. Change the condition inside my_popup_enabled(). Use is_front_page() for the homepage, is_singular( 'post' ) for blog posts, or is_page( 42 ) for one page. Because the same function controls the markup and the script, the popup and its JavaScript always appear together.
Should I use a cookie or localStorage to remember the visitor?
Use localStorage unless your server needs the value. It isn't sent with every request and needs no library. A cookie is only worth it when PHP must read the flag, and on a cached site even that usually backfires.
Why does the popup still appear after I close it?
Check the Console for JavaScript errors first. Then check storage: localStorage is separate per domain, so www and non-www versions don't share it. With a cookie, make sure you set path=/. Private windows and some privacy settings also clear or block storage.
Can I put a form inside the popup?
Yes. Print the form with do_shortcode() inside the <dialog>. With Contact Form 7, listen for the wpcf7mailsent event and close the popup a couple of seconds after a successful submit.
Do popups hurt SEO?
They can, if they cover the content. Google warns that intrusive dialogs and interstitials may lead to poor search performance. A small bar, a corner box, or a popup that opens on scroll or click is a safer choice than a full-screen modal on page load.
Is a cookie notice bar enough for GDPR?
No. A bar with an OK button only informs visitors. GDPR requires opt-in consent before non-essential cookies are set, with a real choice to refuse. Scrolling or continuing to browse doesn't count as consent. For analytics or ad cookies on EU traffic, use a consent management tool.
How is this different from an exit intent popup?
Exit intent is just another trigger. The popup opens when the pointer leaves through the top of the window, which signals the visitor is about to leave. It only works with a mouse, so on phones a delay or scroll trigger does the same job. The exit intent guide linked in Step 3 covers the full version.

Summary

A WordPress popup without a plugin comes down to four things: a <dialog> in the footer, a little CSS, a trigger, and a stored flag that remembers the visitor.

I’d start with localStorage, a scroll or click trigger, and the bar layout on mobile. It’s easy on visitors, works behind any page cache, and fits into three small files in your child theme.

Discussion
[  0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!