Show a slim message bar at the top of every page, such as a sale or shipping notice, that visitors can close.
add_action( 'wp_body_open', function (): void {
$message = 'Free shipping on orders over $75 this week.';
$link = home_url( '/shop/' );
// A new message gets a new id, so people who closed the old one see it.
$id = 'nahnu-bar-' . substr( md5( $message ), 0, 8 );
?>
<div class="nahnu-bar" id="<?php echo esc_attr( $id ); ?>" role="region" aria-label="Announcement" hidden>
<a href="<?php echo esc_url( $link ); ?>"><?php echo esc_html( $message ); ?></a>
<button type="button" aria-label="Close announcement">×</button>
</div>
<style>
.nahnu-bar{display:flex;align-items:center;justify-content:center;gap:12px;padding:10px 48px;background:#15131F;color:#fff;font-size:14px;position:relative}
.nahnu-bar[hidden]{display:none}
.nahnu-bar a{color:#fff;text-decoration:underline}
.nahnu-bar button{position:absolute;right:12px;top:50%;transform:translateY(-50%);border:0;background:none;color:#fff;font-size:20px;line-height:1;cursor:pointer}
</style>
<script>
( function () {
var bar = document.getElementById( <?php echo wp_json_encode( $id ); ?> );
try { if ( localStorage.getItem( bar.id ) ) { return; } } catch ( e ) {}
bar.hidden = false;
bar.querySelector( 'button' ).addEventListener( 'click', function () {
bar.hidden = true;
try { localStorage.setItem( bar.id, '1' ); } catch ( e ) {}
} );
} )();
</script>
<?php
} );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
A sale, a shipping deadline or a planned outage deserves a message at the top of every page. This snippet adds one that visitors can close, and remembers that they did.
The bar is printed on wp_body_open, right after the opening body tag. It starts hidden and a short script shows it unless the visitor already closed it, which avoids a flash of the bar for people who dismissed it.
Closing stores a flag in the browser’s localStorage under an id made from the message. Change the message and the id changes, so everyone sees the new announcement.
wp_body_open(). Almost all themes since 2019 do, including Bricks.Load any page. The bar should appear at the top. Close it and reload: it should stay closed.