Tooltip Shortcode for Terms and Abbreviations
Adds a [wpide_tooltip tip="Explanation"]term[/wpide_tooltip] shortcode that shows a small explanation bubble on hover, tap or keyboard focus.
Opens WPIDE on
Code
add_action( 'wp_enqueue_scripts', function () {
wp_register_style( 'wpide-tooltip', false, array(), '1.0' );
wp_add_inline_style( 'wpide-tooltip', '.wpide-tip{position:relative;border-bottom:1px dotted currentColor;cursor:help;}.wpide-tip:focus-visible{outline:2px solid currentColor;outline-offset:2px;}.wpide-tip__bubble{position:absolute;left:50%;bottom:calc(100% + 8px);transform:translateX(-50%);width:max-content;max-width:min(260px,80vw);padding:6px 10px;border-radius:6px;background:#1d2327;color:#fff;font-size:.85rem;line-height:1.4;font-weight:400;text-align:center;opacity:0;visibility:hidden;transition:opacity .15s ease;z-index:50;pointer-events:none;}.wpide-tip__bubble::after{content:"";position:absolute;top:100%;left:50%;margin-left:-5px;border:5px solid transparent;border-top-color:#1d2327;}.wpide-tip:hover .wpide-tip__bubble,.wpide-tip:focus .wpide-tip__bubble,.wpide-tip:focus-within .wpide-tip__bubble{opacity:1;visibility:visible;}' );
} );
add_shortcode( 'wpide_tooltip', function ( $atts, $content = '' ) {
$atts = shortcode_atts( array( 'tip' => '' ), $atts, 'wpide_tooltip' );
if ( '' === trim( $atts['tip'] ) || '' === trim( $content ) ) {
return esc_html( $content );
}
wp_enqueue_style( 'wpide-tooltip' );
$id = 'wpide-tip-' . wp_unique_id();
return sprintf(
'<span class="wpide-tip" tabindex="0" aria-describedby="%1$s">%2$s<span class="wpide-tip__bubble" role="tooltip" id="%1$s">%3$s</span></span>',
esc_attr( $id ),
esc_html( $content ),
esc_html( $atts['tip'] )
);
} );
Notes
The explanation is also exposed to screen readers. Keep tips short; long text belongs in the content.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.