Create a Slash Command /ai for Init Live Search (using OpenAI API)

The /ai slash command allows Init Live Search to integrate AI-powered responses via ChatGPT (OpenAI). This feature is not built into the plugin by default due to potential API costs. However, you can easily implement it yourself using your personal OpenAI API key.

Create a Slash Command /ai for Init Live Search (using OpenAI API)

Overview

The /ai command is not included by default because enabling it out of the box could lead to unexpected costs for users. Init Live Search allows developers to register their own slash commands using just 3 code snippets: a PHP filter to modify the query, a command declaration filter, and a JavaScript event handler.

Step 1: Register the /ai slash command and its suggestion

add_filter('init_plugin_suite_live_search_commands', function ($commands) {
    $commands['ai'] = __('Ask AI (OpenAI)', 'init-live-search');
    return $commands;
});

Step 2: Prevent normal post querying for /ai

add_filter('init_plugin_suite_live_search_query_args', function ($args, $mode, $request) {
    if ($mode === 'recent' && $request->get_param('term') === '/ai') {
        $args['post__in'] = [0]; // prevent querying posts
    }
    return $args;
}, 10, 3);

Step 3: Call the OpenAI API from JavaScript

Listen for the ils:search-started event and make a request to your custom REST endpoint to get a response from OpenAI:

window.addEventListener('ils:search-started', (e) => {
  const term = (e.detail?.term || '').trim();
  if (!term.startsWith('/ai ')) return;

  const prompt = term.replace('/ai', '').trim();
  if (!prompt) return;

  window.ilsHelpers.showLoading();

  fetch('/wp-json/init/v1/ai?prompt=' + encodeURIComponent(prompt))
    .then(res => res.json())
    .then(data => {
      const html = `<div class="ils-ai-answer">${data.answer || 'No response'}</div>`;
      window.ilsHelpers.setRawContent(html);
    })
    .catch(() => {
      window.ilsHelpers.showMessage('Error contacting AI');
    });
});

Step 4: Create the /wp-json/init/v1/ai endpoint

add_action('rest_api_init', function () {
    register_rest_route('init/v1', '/ai', [
        'methods'  => 'GET',
        'callback' => function ($request) {
            $key = get_option('init_ai_key');
            if (!$key) return rest_ensure_response(['answer' => 'AI disabled.']);

            $prompt = sanitize_text_field($request->get_param('prompt'));
            $res = wp_remote_post('https://api.openai.com/v1/chat/completions', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $key,
                    'Content-Type'  => 'application/json',
                ],
                'body' => json_encode([
                    'model'    => 'gpt-3.5-turbo',
                    'messages' => [
                        ['role' => 'system', 'content' => 'You are an AI assistant for a WordPress website.'],
                        ['role' => 'user', 'content' => $prompt],
                    ],
                ]),
            ]);

            $json = json_decode(wp_remote_retrieve_body($res), true);
            return ['answer' => $json['choices'][0]['message']['content'] ?? 'No reply'];
        },
    ]);
});

Security considerations for the /ai slash command

The /wp-json/init/v1/ai endpoint is a public REST API. If you do not restrict access, anyone can send prompts and use your OpenAI API key — even without visiting your website.

To prevent abuse and unexpected costs, it is strongly recommended to:

  • Allow only logged-in users to access the API (via is_user_logged_in()).
  • Limit prompt length (e.g., max 300 characters).
  • Throttle requests per IP using transient caching (e.g., one request every 10 seconds).
  • (Optional) Require a secret token if exposing the endpoint externally.

Never leave the endpoint fully open without restrictions — a simple spam script could drain your API quota and cost you money.

Conclusion

With just 3 code snippets and a simple REST endpoint, you can turn Init Live Search into a mini ChatGPT assistant. This feature is not bundled with the plugin, but the system is fully open for you to customize. Note: OpenAI API usage is not free, and the plugin is not responsible for any cost incurred from your API key.

Comments


  • No comments yet.

Init Toolbox

Press Ctrl + \ on desktop, or swipe left anywhere on mobile.

Login