Gemini chatbot : create for WordPress Plugin

chatbot_gemani_php_javascript_wordpress_ipdata_code

Let’s create Gemini chatbot into WordPress so you can use it anywhere on your site via a shortcode (e.g., [gemini_chatbot]).

Step 1: Create a WordPress Plugin

  1. Go to your WordPress installation:
    wp-content/plugins/
    
            
  2. Create a new folder:
    gemini-chatbot
    
            
  3. Inside it, create a file:
    gemini-chatbot.php
            

Step 2: Plugin Code (gemini-chatbot.php)

 

<?php
/*
Plugin Name: Gemini Chatbot
Description: A chatbot powered by Google Gemini API.
Version: 1.0
Author: Your Name
*/

if (!defined('ABSPATH')) exit;

// Enqueue JS + CSS
function gemini_chatbot_enqueue_scripts() {
    wp_enqueue_script('gemini-chatbot-js', plugin_dir_url(__FILE__) . 'gemini-chatbot.js', ['jquery'], '1.0', true);
    wp_localize_script('gemini-chatbot-js', 'geminiChatbot', [
        'ajaxurl' => admin_url('admin-ajax.php'),
    ]);

    wp_enqueue_style('gemini-chatbot-css', plugin_dir_url(__FILE__) . 'gemini-chatbot.css');
}
add_action('wp_enqueue_scripts', 'gemini_chatbot_enqueue_scripts');

// Shortcode to display chatbot
function gemini_chatbot_shortcode() {
    ob_start(); ?>
    <div class="gemini-chatbox">
        <div class="messages" id="gemini-messages"></div>
        <input type="text" id="gemini-input" placeholder="Type a message..." />
        <button onclick="geminiSend()">Send</button>
        <button onclick="geminiReset()">Reset</button>
    </div>
    <?php
    return ob_get_clean();
}
add_shortcode('gemini_chatbot', 'gemini_chatbot_shortcode');

// Handle AJAX request
function gemini_chatbot_ajax() {
    session_start();
    $apiKey = "YOUR_GEMINI_API_KEY"; // 🔑 Replace with your key

    $userMessage = sanitize_text_field($_POST['message']);

    if (!isset($_SESSION['gemini_history'])) {
        $_SESSION['gemini_history'] = [];
    }

    $_SESSION['gemini_history'][] = [
        "role" => "user",
        "parts" => [["text" => $userMessage]]
    ];

    $data = ["contents" => $_SESSION['gemini_history']];

    $ch = curl_init("https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=" . $apiKey);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
    $response = curl_exec($ch);
    curl_close($ch);

    $responseData = json_decode($response, true);
    $botReply = $responseData['candidates'][0]['content']['parts'][0]['text'] ?? "⚠️ No response from Gemini";

    $_SESSION['gemini_history'][] = [
        "role" => "model",
        "parts" => [["text" => $botReply]]
    ];

    wp_send_json(["reply" => $botReply]);
}
add_action('wp_ajax_gemini_chatbot', 'gemini_chatbot_ajax');
add_action('wp_ajax_nopriv_gemini_chatbot', 'gemini_chatbot_ajax');

// Handle reset
function gemini_chatbot_reset() {
    session_start();
    $_SESSION['gemini_history'] = [];
    wp_send_json(["status" => "reset"]);
}
add_action('wp_ajax_gemini_reset', 'gemini_chatbot_reset');
add_action('wp_ajax_nopriv_gemini_reset', 'gemini_chatbot_reset');

        

Step 3: JavaScript (gemini-chatbot.js)

 

async function geminiSend() {
    const input = document.getElementById("gemini-input");
    const message = input.value.trim();
    if (!message) return;

    addGeminiMessage(message, "user");
    input.value = "";

    const response = await fetch(geminiChatbot.ajaxurl + "?action=gemini_chatbot", {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: "message=" + encodeURIComponent(message)
    });

    const data = await response.json();
    addGeminiMessage(data.reply, "bot");
}

function addGeminiMessage(text, type) {
    const messagesDiv = document.getElementById("gemini-messages");
    const msgDiv = document.createElement("div");
    msgDiv.className = "msg " + type;
    msgDiv.textContent = text;
    messagesDiv.appendChild(msgDiv);
    messagesDiv.scrollTop = messagesDiv.scrollHeight;
}

async function geminiReset() {
    await fetch(geminiChatbot.ajaxurl + "?action=gemini_reset", { method: "POST" });
    document.getElementById("gemini-messages").innerHTML = "";
}

        

Step 4: CSS (gemini-chatbot.css)

 

.gemini-chatbox {
    width: 100%;
    max-width: 400px;
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0,0,0,.1);
    padding: 15px;
}
.gemini-chatbox .messages {
    height: 300px;
    overflow-y: auto;
    border: 1px solid #ddd;
    padding: 10px;
    margin-bottom: 10px;
    border-radius: 5px;
}
.msg {
    margin: 5px 0;
    padding: 8px;
    border-radius: 6px;
}
.msg.user { background: #d1e7dd; text-align: right; }
.msg.bot { background: #e2e3e5; text-align: left; }

        

Step 5: Usage

  1. Upload this plugin folder to wp-content/plugins/.

  2. Activate Gemini Chatbot in WordPress admin.

  3. Add shortcode in any post or page:

[gemini_chatbot]
        
Previous Article

full interactive chatbot using PHP (backend) + HTML/CSS + JavaScript (frontend) with the Gemini API.

Next Article

Enquiry sent automatically to WhatsApp

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨