Halloween Sale 15% off Ends in See the plans
PHP

Translatable Announcement Bar With WPML

Shows a slim announcement bar at the top of every page whose text you translate in WPML > String Translation, so each language gets its own message.

Don’t have WPIDE yet? Install it on your site

Code

$wpide_text = 'Free shipping on orders over $50 this week only.'; // Default-language text.
$wpide_link = '/shop/';                                          // Optional link, or ''.

add_action( 'admin_init', function () use ( $wpide_text, $wpide_link ) {
    if ( ! defined( 'ICL_SITEPRESS_VERSION' ) ) {
        return;
    }
    do_action( 'wpml_register_single_string', 'WPIDE Snippets', 'Announcement text', $wpide_text );
    if ( $wpide_link ) {
        do_action( 'wpml_register_single_string', 'WPIDE Snippets', 'Announcement link', $wpide_link );
    }
} );

add_action( 'wp_body_open', function () use ( $wpide_text, $wpide_link ) {
    if ( ! defined( 'ICL_SITEPRESS_VERSION' ) ) {
        return;
    }

    $text = apply_filters( 'wpml_translate_single_string', $wpide_text, 'WPIDE Snippets', 'Announcement text' );
    $link = $wpide_link ? apply_filters( 'wpml_translate_single_string', $wpide_link, 'WPIDE Snippets', 'Announcement link' ) : '';

    if ( '' === trim( (string) $text ) ) {
        return;
    }

    if ( $link && 0 === strpos( $link, '/' ) ) {
        $link = apply_filters( 'wpml_permalink', home_url( $link ) );
    }

    echo '<div class="wpide-announcement" role="region" aria-label="' . esc_attr__( 'Announcement' ) . '" style="background:#1d2327;color:#fff;text-align:center;padding:8px 16px;font-size:14px">';
    echo $link ? '<a href="' . esc_url( $link ) . '" style="color:inherit">' . esc_html( $text ) . '</a>' : esc_html( $text );
    echo '</div>';
} );

Notes

Edit $wpide_text and $wpide_link, visit the dashboard once, then translate the strings under the "WPIDE Snippets" domain in String Translation.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.