WordPress Tooltip Funktion

Wie nutzen?

Füge im Text einfach {{tooltip:Wort das erklärt wird###Erklärung zum Wort dazu}}. PHP und JS prüft die {{, ### & }} und wandelt diese richtig.

CSS
/* Tooltip */
.tooltip-wrap {
  position: relative;
  display: inline-block;
}

.tooltip-trigger {
  border-bottom: 1px dotted currentColor;
  cursor: help;
}

.tooltip {
  visibility: hidden;
  opacity: 0;
  position: absolute;
  bottom: calc(100% + 6px);
  left: 0;
  transform: none;
  background: #222;
  color: #fff;
  padding: 6px 10px;
  border-radius: 0;
  font-size: 0.85em;
  white-space: normal;
  max-width: 400px;
  width: max-content;
  pointer-events: none;
  transition: opacity 0.2s;
  z-index: 100;
}

/* Sichtbar bei Hover auf Trigger oder Tooltip selbst */
.tooltip-wrap:hover .tooltip,
.tooltip-trigger:focus + .tooltip {
  visibility: visible;
  opacity: 1;
  pointer-events: auto;
}
JavaScript
// tooltip excape support
document.addEventListener('keydown', e => {
  if (e.key === 'Escape') {
    document.activeElement?.blur();
  }
});

document.querySelectorAll('.tooltip-trigger').forEach(trigger => {
  trigger.addEventListener('mouseenter', fixTooltipPosition);
  trigger.addEventListener('focus', fixTooltipPosition);
});

function fixTooltipPosition(e) {
  const tooltip = e.target.nextElementSibling;

  if (window.innerWidth <= 768) {
    tooltip.style.visibility = 'visible';
    const rect = e.target.getBoundingClientRect();
    tooltip.style.visibility = '';
    tooltip.style.position = 'fixed';
    tooltip.style.left = '16px';
    tooltip.style.right = '16px';
    tooltip.style.width = 'auto';
    tooltip.style.maxWidth = window.innerWidth <= 768 ? 'none' : '400px';
    tooltip.style.bottom = 'auto';
    tooltip.style.top = (rect.top - tooltip.offsetHeight - 8) + 'px';
    tooltip.style.transform = 'none';
  } else {
    tooltip.style.position = '';
    tooltip.style.left = '60%';
    tooltip.style.transform = 'translateX(-60%)';
    tooltip.style.right = 'auto';
    tooltip.style.width = '';
    tooltip.style.maxWidth = '';
    tooltip.style.bottom = '';
    tooltip.style.top = '';
  }
}
PHP
/* Tooltip Funktionalität */
add_filter('the_content', function($content) {
    return preg_replace_callback(
        '/\{\{tooltip:(.+?)###(.+?)\}\}/',
        function($m) {
            $id = 'tip-' . sanitize_title($m[1]);
            return '<span class="tooltip-wrap"><span class="tooltip-trigger" aria-describedby="' . $id . '" tabindex="0">' . esc_html($m[1]) . '</span><span class="tooltip" role="tooltip" id="' . $id . '">' . esc_html($m[2]) . '</span></span>';
        },
        $content
    );
});