플러그인 없이 워드프레스에서 도구 설명 추가하기

Seleccionar idioma
플러그인 없이 워드프레스에서 도구 설명 추가하기
여기에 사용된 툴팁의 예

툴팁이라는 용어는 영어로 고유하게 번역된 용어가 없으며, 사용되는 문맥에 따라 "툴팁", "도움말 풍선", "팝업 설명" 또는 "도움말 텍스트"로 설명할 수 있습니다.

도구 설명은 요소를 클릭하거나 마우스를 가리키면 요소와 상호 작용할 때 표시되는 팝업 메시지입니다. 이러한 툴팁은 영구적인 공간을 차지하지 않고 추가 정보를 제공하는 데 사용됩니다. 인터페이스의 아이콘, 기술 용어 또는 동작을 설명하는 데 이상적입니다.

툴팁이 SEO에 해가 되나요, 도움이 되나요?

글쎄요, 거의 모든 것이 그렇듯이 답은 항상 상황에 따라 다릅니다. SEO 순수주의자들은 Google이 '숨겨진' 콘텐츠나 마스킹된 콘텐츠를 좋아하지 않으며 이러한 콘텐츠 사용에 가혹한 불이익을 준다고 경고하지만, 이는 콘텐츠를 '식인'할 수 있는 악용 사례의 경우 극단적인 경우입니다. 하지만 일정한 균형과 최소한의 논리로 툴팁을 사용하면 도움이 될 수 있습니다.

툴팁 사용의 장점

대체로 이러한 메시지는 친근하고 눈에 거슬리지 않는다면 사용자 경험의 다양한 측면을 개선하는 데 기여할 수 있습니다. 무엇보다도 이탈률을 줄이고 접근성을 개선할 수 있습니다. 또한 기본 콘텐츠에 자연스럽게 어울리지 않는 추가 키워드를 사용할 수 있는 기회를 제공하여 시맨틱 SEO에 도움이 될 수 있습니다.

또한 클릭률을 향상시킬 수 있습니다. 탐색 또는 콜투액션 버튼에 툴팁을 제공함으로써 사용자를 보다 효과적으로 안내하여 클릭률을 높일 수 있습니다. 하지만 이 모든 것이 가능하려면 몇 가지 최소한의 가이드라인을 따라야 합니다.

외관, 콘텐츠 및 운영에 대한 권장 사항

  • 화면 리더와 검색 엔진이 포함된 정보에 액세스할 수 있도록 HTML 요소와 ARIA 속성을 사용합니다.
  • 툴팁은 짧아야 합니다. 팝업에서 방대한 양의 정보를 읽으려는 사람은 아무도 없으며 콘텐츠의 대부분을 다루게 될 것입니다. 최소한의 정확하고 필요한 정보를 포함해야 하며, 사용자가 작업을 수행하거나 완료할 때 중요하지 않아야 합니다.
  • 콘텐츠는 중복되거나 반복되어서는 안 되며, 유용하고 필요한 정보를 추가로 제공하고 '중복 콘텐츠'를 피하기 위해 콘텐츠에서 반복되지 않도록 해야 합니다.
  • 커서를 움직이면 사라지는 툴팁은 가급적 피하거나 많은 정보 및/또는 콘텐츠를 포함하지 않는 메시지에만 사용하세요. 클릭할 때마다 표시되고 화면의 아무 곳이나 다시 클릭하면 닫히는 것이 가장 이상적입니다.
  • 가독성이 좋고 크기가 올바른지 확인하세요.
  • 20가지 다른 디자인의 툴팁 아이콘이나 툴팁 링크를 추가하면 혼란만 야기할 뿐입니다. 고정되고 일관된 디자인을 사용하면 방문자가 한눈에 쉽게 식별할 수 있습니다.
  • 무리하지 말고 관련성이 있거나 필요한 보완 정보에 쉽게 액세스할 수 있다고 생각되는 경우에만 추가하도록 전략을 잘 계획하세요.

코드의 특징 및 기능

이 사례에는 배경이 투명한 .png 이미지가 사용되었습니다.

여기에서 최종 결과물이 작동하는지 테스트할 수 있습니다 [도구 설명 텍스트="jrmora.com에서 사용된 예제 도구 설명" 위치="자동"].

이미지의 URL은 이 줄의 작은따옴표 사이에 추가됩니다:

$default_image = 'URL-de-tu-imagen';

아이콘과 같이 SVG HTML 아이콘을 사용하도록 코드를 수정하면 색상, 배경, 두께 등을 더 쉽게 변경할 수 있습니다.

화면 가장자리를 피하기 위한 지능형 자동 위치 조정. 즉, 상단 가장자리에 접근하면 툴팁이 하단에 표시되고 생동감 있게 표시됩니다.

사용자 지정 가능한 스타일로 툴팁 내에 모든 기능을 갖춘 링크를 추가할 수 있습니다. 링크를 추가하는 것은 바람직하지 않지만 경우에 따라 링크를 추가해야 할 수도 있습니다. 툴팁에 링크가 포함된 경우 클릭하기 쉽도록 200밀리초 동안 자동으로 숨겨집니다.

보안 HTML 지원. 지원:

<strong>, <em>, <a>, <br>, <span>

위치, 고정 및 적응형 속성.

Atributos de posición disponibles:  position="auto" (default), top, bottom, left, right

ARIA 속성 (aria-expanded, role="tooltip").

반응형 디자인.

모바일 적용 가능 (클릭 가능한 토글).

크기 조정, 회전 또는 이동 시 재설정하기

주요 CSS 클래스:

.tooltip-container /* Contenedor principal */
.tooltip-trigger  /* Botón/icono que activa el tooltip */
.tooltip          /* Caja del mensaje emergente */
.tooltip-arrow    /* Flecha indicadora */

JS의 주요 기능:

calculateBestPosition() // Determina si colocar el tooltip arriba, abajo, etc.
showTooltip()          // Muestra el tooltip
hideTooltip()          // Oculta el tooltip con retraso

단축 코드의 예

[tooltip text="Texto a mostrar"] 

[tooltip text="Texto a mostrar <strong>en negrita</strong> donde sea" position="auto"] 

[tooltip text="Texto <strong>importante</strong> y <em>énfasis</em>"]

[tooltip text="<a href='https://ejemplo.com' target='_blank'>Visite nuestro sitio</a>"]

이 코드는 제가 특정한 필요에 따라 사용한 코드입니다. 시작점으로 이해하세요. 매우 개선할 수 있습니다. CSS와 JS를 분리하고(또는 자바스크립트를 사용하지 않고도 고려할 수 있습니다) 아이콘을 표시하지 않고 콘텐츠의 단어에도 적용될 수 있도록 조정할 수 있습니다.

템플릿이 업데이트될 때 변경 사항을 유지하려면 항상 그렇듯이 템플릿 또는 하위 테마의 functions.php에 추가하기만 하면 됩니다.

코드

/**
 * Shortcode para tooltip con ajuste automático 
 * Un ejemplo de uso: [tooltip text="Texto <a href='#'>enlace</a>" position="auto"]
 */
function custom_tooltip_shortcode($atts) {
    $default_image = 'URL-de-tu-imagen';
    
    $atts = shortcode_atts(
        array(
            'text' => __('Información adicional', 'text-domain'),
            'position' => 'auto',
            'color' => '#6a0000',
            'shadow' => '#9c9c9c',
            'width' => '18px',
            'id' => 'tooltip-' . uniqid()
        ),
        $atts,
        'tooltip'
    );

    // HTML permitido
    $allowed_html = array(
        'strong' => array(),
        'b' => array(),
        'em' => array(),
        'i' => array(),
        'br' => array(),
        'span' => array(
            'style' => array(),
            'class' => array()
        ),
        'a' => array(
            'href' => array(),
            'title' => array(),
            'target' => array(),
            'style' => array(),
            'rel' => array()
        )
    );
    
    $text = wp_kses($atts['text'], $allowed_html);
    $position = in_array($atts['position'], ['top', 'bottom', 'left', 'right', 'auto']) ? $atts['position'] : 'auto';
    $color = sanitize_hex_color($atts['color']);
    $shadow = sanitize_hex_color($atts['shadow']);
    $width = esc_attr($atts['width']);
    $id = sanitize_html_class($atts['id']);

    $output = '
    <span class="tooltip-container" data-position="' . esc_attr($position) . '">
        <button class="tooltip-trigger" aria-describedby="' . $id . '" aria-expanded="false">
            <img src="' . esc_url($default_image) . '" width="' . $width . '" alt="" aria-hidden="true"/>
        </button>
        <span id="' . $id . '" role="tooltip" class="tooltip" style="background-color: ' . $color . '; box-shadow: 0 5px 10px ' . $shadow . ';">
            ' . $text . '
            <span class="tooltip-arrow"></span>
        </span>
    </span>';

    return $output;
}
add_shortcode('tooltip', 'custom_tooltip_shortcode');

/**
 * Estilos CSS optimizados para enlaces
 */
function add_tooltip_styles() {
    echo '
    <style>
    .tooltip-container {
        display: inline-block;
        position: relative;
        vertical-align: middle;
    }

    .tooltip-trigger {
        background: none;
        border: none;
        padding: 0;
        margin: 0 2px;
        cursor: pointer;
        line-height: 1;
    }

    .tooltip {
        position: absolute;
        color: #fff;
        padding: 10px 12px;
        border-radius: 4px;
        font-size: 14px;
        line-height: 1.5;
        width: 220px;
        max-width: 90vw;
        text-align: left;
        visibility: hidden;
        opacity: 0;
        transition: opacity 0.25s ease;
        z-index: 100000;
        pointer-events: none;
    }

    .tooltip a {
        color: #fff !important;
        text-decoration: underline;
        pointer-events: auto !important;
    }

    .tooltip * {
        pointer-events: auto;
    }

    .tooltip-arrow {
        position: absolute;
        width: 0;
        height: 0;
        border: 7px solid transparent;
    }

    /* Posiciones dinámicas */
    .tooltip[data-position="top"] {
        bottom: 100%;
        left: 50%;
        transform: translateX(-50%);
        margin-bottom: 10px;
    }
    .tooltip[data-position="top"] .tooltip-arrow {
        top: 100%;
        left: 50%;
        transform: translateX(-50%);
        border-top-color: inherit;
    }

    .tooltip[data-position="bottom"] {
        top: 100%;
        left: 50%;
        transform: translateX(-50%);
        margin-top: 10px;
    }
    .tooltip[data-position="bottom"] .tooltip-arrow {
        bottom: 100%;
        left: 50%;
        transform: translateX(-50%);
        border-bottom-color: inherit;
    }

    .tooltip[data-position="left"] {
        top: 50%;
        right: 100%;
        transform: translateY(-50%);
        margin-right: 10px;
    }
    .tooltip[data-position="left"] .tooltip-arrow {
        top: 50%;
        right: 0;
        transform: translate(50%, -50%);
        border-left-color: inherit;
    }

    .tooltip[data-position="right"] {
        top: 50%;
        left: 100%;
        transform: translateY(-50%);
        margin-left: 10px;
    }
    .tooltip[data-position="right"] .tooltip-arrow {
        top: 50%;
        left: 0;
        transform: translate(-50%, -50%);
        border-right-color: inherit;
    }

    /* Interacción */
    .tooltip-trigger:hover + .tooltip,
    .tooltip-trigger:focus + .tooltip,
    .tooltip-trigger[aria-expanded="true"] + .tooltip {
        visibility: visible;
        opacity: 1;
    }
    </style>
    ';
}
add_action('wp_head', 'add_tooltip_styles');

/**
 * JavaScript corregido para enlaces clickeables con retraso
 */
function add_tooltip_scripts() {
    echo '
    <script>
    document.addEventListener("DOMContentLoaded", function() {
        // Configurar todos los tooltips
        document.querySelectorAll(".tooltip-container").forEach(function(container) {
            const tooltip = container.querySelector(".tooltip");
            const trigger = container.querySelector(".tooltip-trigger");
            let hoverTimeout;
            let isMouseInTooltip = false;
            const position = container.getAttribute("data-position");

            // Función para calcular posición automática
            function calculateBestPosition() {
                const rect = trigger.getBoundingClientRect();
                const viewportHeight = window.innerHeight;
                const viewportWidth = window.innerWidth;
                const tooltipHeight = 150; // Altura estimada
                const tooltipWidth = 220; // Ancho estimado
                
                const space = {
                    top: rect.top,
                    bottom: viewportHeight - rect.bottom,
                    left: rect.left,
                    right: viewportWidth - rect.right
                };
                
                // Determinar mejor posición disponible
                if (space.top >= tooltipHeight || (space.top >= space.bottom && space.top > 50)) {
                    return "top";
                } else if (space.bottom >= tooltipHeight) {
                    return "bottom";
                } else if (space.right >= tooltipWidth) {
                    return "right";
                } else if (space.left >= tooltipWidth) {
                    return "left";
                }
                return "top"; // Default
            }

            // Actualizar posición (solo para "auto")
            function updatePosition() {
                if (position === "auto") {
                    tooltip.setAttribute("data-position", calculateBestPosition());
                }
            }

            // Mostrar tooltip
            function showTooltip() {
                clearTimeout(hoverTimeout);
                tooltip.style.visibility = "visible";
                tooltip.style.opacity = "1";
                trigger.setAttribute("aria-expanded", "true");
            }

            // Ocultar tooltip con retraso de 200ms
            function hideTooltip() {
                if (!isMouseInTooltip) {
                    hoverTimeout = setTimeout(() => {
                        tooltip.style.visibility = "hidden";
                        tooltip.style.opacity = "0";
                        trigger.setAttribute("aria-expanded", "false");
                    }, 200); // Retraso clave para enlaces
                }
            }

            // Inicializar posición
            updatePosition();

            // Eventos para el botón
            trigger.addEventListener("mouseenter", showTooltip);
            trigger.addEventListener("mouseleave", hideTooltip);
            trigger.addEventListener("focus", showTooltip);
            trigger.addEventListener("blur", hideTooltip);

            // Eventos para el tooltip (mejorados para enlaces)
            tooltip.addEventListener("mouseenter", function() {
                isMouseInTooltip = true;
                clearTimeout(hoverTimeout); // Cancelar ocultamiento
            });

            tooltip.addEventListener("mouseleave", function() {
                isMouseInTooltip = false;
                hideTooltip(); // Iniciar retraso para ocultar
            });

            // Click en el botón (para móviles)
            trigger.addEventListener("click", function(e) {
                e.preventDefault();
                if (tooltip.style.visibility === "visible") {
                    hideTooltip();
                } else {
                    showTooltip();
                }
            });

            // Reajustar posición en eventos
            if (position === "auto") {
                window.addEventListener("resize", updatePosition);
                window.addEventListener("scroll", updatePosition, { passive: true });
            }
        });

        // Cerrar tooltips al hacer clic fuera (excepto en enlaces)
        document.addEventListener("click", function(e) {
            if (!e.target.closest(".tooltip-container") && !e.target.closest(".tooltip a")) {
                document.querySelectorAll(".tooltip").forEach(function(tooltip) {
                    tooltip.style.visibility = "hidden";
                    tooltip.style.opacity = "0";
                });
                document.querySelectorAll(".tooltip-trigger").forEach(function(trigger) {
                    trigger.setAttribute("aria-expanded", "false");
                });
            }
        });
    });
    </script>
    ';
}
add_action('wp_footer', 'add_tooltip_scripts');

관련 문서

Este blog se aloja en LucusHost

LucusHost, el mejor hosting