Add Voice Search Feature Website Code

Functions.php


/**
 * Responsive Header Voice Search
 * Shortcode: [header_voice_search]
 */

add_shortcode('header_voice_search', function () {

    static $instance = 0;
    $instance++;

    $id = 'wpvs-' . $instance;

    ob_start();
    ?>

    <form id="<?php echo esc_attr($id); ?>"
          class="wpvs-form"
          role="search"
          method="get"
          action="<?php echo esc_url(home_url('/')); ?>">

        <div class="wpvs-bar">

            <input
                type="search"
                name="s"
                class="wpvs-input"
                placeholder="Search anything..."
                aria-label="Search website"
                value="<?php echo esc_attr(get_search_query()); ?>"
                required
            >

            <button type="button"
                    class="wpvs-mic"
                    aria-label="Start voice search"
                    title="Search by voice">

                <svg viewBox="0 0 24 24"
                     width="22" height="22"
                     fill="none"
                     stroke="currentColor"
                     stroke-width="2"
                     stroke-linecap="round"
                     stroke-linejoin="round"
                     aria-hidden="true">
                    <rect x="9" y="2" width="6"
                          height="12" rx="3"/>
                    <path d="M5 10a7 7 0 0 0 14 0"/>
                    <path d="M12 17v5"/>
                    <path d="M8 22h8"/>
                </svg>

            </button>

            <button type="submit"
                    class="wpvs-submit">
                Search
            </button>

        </div>

        <div class="wpvs-status"
             role="status"
             aria-live="polite"></div>

    </form>

    <style>
    .wpvs-form {
        width: 100%;
        max-width: 650px;
        margin: 0 auto;
        font-family: inherit;
    }

    .wpvs-bar {
        display: flex;
        align-items: center;
        width: 100%;
        min-height: 48px;
        background: #fff;
        border: 1px solid #d8dce3;
        border-radius: 10px;
        overflow: hidden;
        transition: border-color .2s, box-shadow .2s;
    }

    .wpvs-bar:focus-within {
        border-color: #2563eb;
        box-shadow: 0 0 0 3px rgba(37,99,235,.12);
    }

    .wpvs-input {
        flex: 1;
        width: 100%;
        min-width: 0;
        height: 48px;
        padding: 0 14px !important;
        border: none !important;
        outline: none !important;
        box-shadow: none !important;
        background: transparent !important;
        color: #111827 !important;
        font-size: 15px;
    }

    .wpvs-input:focus {
        box-shadow: none !important;
    }

    .wpvs-mic {
        flex-shrink: 0;
        width: 44px;
        height: 44px;
        display: flex;
        align-items: center;
        justify-content: center;
        border: none !important;
        background: transparent !important;
        color: #2563eb !important;
        cursor: pointer;
        padding: 0 !important;
    }

    .wpvs-mic:hover {
        color: #1d4ed8 !important;
    }

    .wpvs-mic.wpvs-listening {
        color: #dc2626 !important;
        animation: wpvs-pulse 1s infinite;
    }

    .wpvs-mic:disabled {
        opacity: .4;
        cursor: not-allowed;
    }

    .wpvs-submit {
        flex-shrink: 0;
        height: 48px;
        padding: 0 20px !important;
        border: none !important;
        border-radius: 0 !important;
        background: #2563eb !important;
        color: #fff !important;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
    }

    .wpvs-submit:hover {
        background: #1d4ed8 !important;
    }

    .wpvs-status {
        font-size: 12px;
        line-height: 1.5;
        margin-top: 4px;
    }

    .wpvs-status:empty {
        display: none;
    }

    @keyframes wpvs-pulse {
        0%, 100% { opacity: 1; transform: scale(1); }
        50% { opacity: .5; transform: scale(1.12); }
    }

    @media (max-width: 767px) {
        .wpvs-form {
            max-width: 100%;
        }

        .wpvs-bar {
            min-height: 44px;
            border-radius: 8px;
        }

        .wpvs-input {
            height: 44px;
            font-size: 14px;
            padding: 0 10px !important;
        }

        .wpvs-mic {
            width: 40px;
            height: 40px;
        }

        .wpvs-submit {
            height: 44px;
            padding: 0 12px !important;
            font-size: 13px;
        }
    }
    </style>

    <script>
    (function () {
        const form = document.getElementById(
            <?php echo wp_json_encode($id); ?>
        );

        if (!form) return;

        const input = form.querySelector('.wpvs-input');
        const mic = form.querySelector('.wpvs-mic');
        const status = form.querySelector('.wpvs-status');

        const SpeechRecognition =
            window.SpeechRecognition ||
            window.webkitSpeechRecognition;

        if (!SpeechRecognition) {
            mic.disabled = true;
            mic.title = 'Voice search not supported';
            status.textContent =
                'Voice search is unavailable in this browser.';
            return;
        }

        const recognition = new SpeechRecognition();

        recognition.lang = 'en-IN';
        recognition.continuous = false;
        recognition.interimResults = false;
        recognition.maxAlternatives = 1;

        let listening = false;
        let recognized = false;

        mic.addEventListener('click', function () {

            if (listening) {
                recognition.stop();
                return;
            }

            recognized = false;

            try {
                recognition.start();
            } catch (error) {
                status.textContent = 'Please try again.';
            }
        });

        recognition.onstart = function () {
            listening = true;
            mic.classList.add('wpvs-listening');
            mic.setAttribute('aria-label', 'Stop voice search');
            status.textContent = 'Listening... Speak now.';
        };

        recognition.onresult = function (event) {

            const transcript =
                event.results[0][0].transcript.trim();

            if (!transcript) return;

            recognized = true;
            input.value = transcript;

            status.textContent = 'Searching: ' + transcript;

            if (form.requestSubmit) {
                form.requestSubmit();
            } else {
                form.submit();
            }
        };

        recognition.onerror = function (event) {

            const messages = {
                'not-allowed': 'Microphone permission denied.',
                'no-speech': 'No speech detected. Try again.',
                'audio-capture': 'Microphone not available.',
                'network': 'Speech service network error.'
            };

            status.textContent =
                messages[event.error] ||
                'Voice search failed. Please try again.';
        };

        recognition.onend = function () {

            listening = false;
            mic.classList.remove('wpvs-listening');
            mic.setAttribute('aria-label', 'Start voice search');

            if (!recognized &&
                status.textContent === 'Listening... Speak now.') {
                status.textContent = 'Voice search stopped.';
            }
        };

    })();
    </script>

    <?php
    return ob_get_clean();
});

Short Code

[header_voice_search]

Leave a Comment

Prove your humanity: 4   +   2   =