Skip to content

How to Integrate ChatGPT into WordPress Without Exposing Your Key

How to Integrate ChatGPT into WordPress Without Exposing Your Key

You can integrate ChatGPT into WordPress with a plugin, with the AI Client built into WordPress 7, or with your own code. The plugin route takes the least effort, while custom code gives you the most control over cost and safety.

We tested the sample code in this guide on a WordPress 7.1 test site in October 2026. It ran against a local stand-in that follows OpenAI’s documented request and response shapes. We did not send live prompts to OpenAI. We also checked OpenAI’s pricing, model, and deprecation pages on October 14, 2026.

Next come a comparison of the three routes, the costs, and the model to pick. After that you get the plugin steps, a tested chat box, and the mistakes to avoid.

How to Integrate ChatGPT into WordPress in Three Ways

You can integrate ChatGPT into WordPress by installing a chatbot plugin, by using the AI Client in WordPress 7, or by writing a small plugin. All three need an OpenAI API key. They differ in who holds that key and who controls the limits.

Three ways to integrate ChatGPT into WordPress
RouteYou needWhere the key livesBest for
PluginAn API key and a pluginThe plugin settingsA chat widget or writing tools
AI ClientWordPress 7, a provider plugin, and a developerSettings > ConnectorsPlugins that share one key
Your own codePHP and JavaScriptA constant in wp-config.phpA custom chat box with strict limits

Pick a plugin if you want a chat widget today and can accept its defaults. Pick the AI Client if you build plugins and want one place for credentials. Pick your own code if you need to control who can ask, how often, and what it costs.

The old advice for this topic was to paste a key into a code snippet and call the API from a public AJAX action. That pattern is unsafe, and the mistakes section below explains why. For a broader view of AI tools on a site, see our guide to AI integration with WordPress.

How Much Does It Cost to Connect ChatGPT to WordPress?

Connecting ChatGPT to WordPress costs whatever the OpenAI API charges per token, plus the price of any plugin you choose. A ChatGPT subscription does not cover it. OpenAI’s help page for ChatGPT Plus lists API usage as billed separately from the subscription.

OpenAI’s pricing page lists prices per one million tokens. As of October 2026 the small model, gpt-6-luna, costs $0.10 for input and $0.50 for output. The two larger models cost much more. If cost drives your choice, compare it with the open-weight option in our DeepSeek vs ChatGPT breakdown.

OpenAI pricing for gpt-6-luna per million tokens
Source: OpenAI pricing page from October 2026

Say your chat box answers 1,000 questions in a month. Each question plus instructions uses about 500 input tokens, and each answer uses about 200 output tokens.

That is 500,000 input tokens at $0.10 per million, or $0.05. It is also 200,000 output tokens at $0.50 per million, or $0.10. The total is $0.15 for the month.

Note: The example ignores reasoning tokens. Treat $0.15 as a floor. OpenAI counts them toward the output limit you set. That is why the code later in this guide asks for low reasoning effort.

Which OpenAI Model Should You Pick for WordPress?

Pick the small model for a site chat box and move up only if answers are weak. OpenAI’s models page names gpt-6-luna as its most efficient model for focused high-volume tasks. Larger models cost five to 100 times more per token. You pay for power a short answer rarely needs.

ModelInput per 1M tokensOutput per 1M tokensUse it for
gpt-6-luna$0.10$0.50Short site answers
gpt-6.1-sol$2.00$10.00Harder questions
gpt-6-astra$10.00$50.00Complex reasoning

Do not copy gpt-3.5-turbo from older tutorials. OpenAI’s deprecations page lists October 23, 2026 as its shutdown date, with gpt-5.6-terra as the suggested substitute. Any plugin or snippet still pointing at that model will stop answering.

OpenAI deprecations page showing the gpt-3.5-turbo shutdown date of October 23 2026
Source: OpenAI deprecations page from October 2026

The old version of this guide used gpt-3.5-turbo. If you copied its code, change the model now and read the mistakes section below, because the model was not its biggest problem.

How to Add a ChatGPT WordPress Plugin

A ChatGPT WordPress plugin connects your site to the OpenAI API without custom code. You install the plugin, paste your API key into its settings, and place the chat widget or writing tool where you want it. Check each plugin’s update date and tested WordPress version before you install it.

The table uses each plugin’s WordPress.org listing on October 14, 2026. We did not install these plugins for this guide. The numbers describe the listings and are not results from our own tests.

PluginActive installsRatingLast updatedTested up to
AI Engine90,000+4.9 of 5 (870 ratings)October 8, 2026WordPress 7.1.3
AI Puffer10,000+4.6 of 5 (166 ratings)October 11, 2026WordPress 7.1.3
AI ChatBot with ChatGPT by AYS300+5 of 5 (9 ratings)September 30, 2026WordPress 7.1.3
AI Engine plugin page on WordPress.org showing 90000 active installations
Source: WordPress.org from October 2026

Follow these steps for any of them:

  1. Open Plugins > Add Plugin and search for the plugin name.
  2. Install and activate it and then open its settings page.
  3. Paste your OpenAI API key, and choose gpt-6-luna if the plugin lets you pick a model.
  4. Add its chat block or shortcode to one test page, and ask three questions before you publish.

Look for a daily or per-user limit in the plugin settings. If it has none, you are trusting visitors with your OpenAI bill. Our list of the best WordPress chatbot plugins compares more options, including free plans and page weight.

How to Use the WordPress 7 AI Client With OpenAI

The WordPress 7 AI Client lets a plugin send a prompt to an AI model without handling the API key itself. Core provides the function and the Connectors screen. The official dev note states that WordPress Core does not bundle any AI providers. You add a provider plugin first.

On our WordPress 7.1.3 test site, Settings > Connectors listed Anthropic, Google and OpenAI with an Install button for each.

OpenAI connector on the WordPress Settings Connectors screen

WordPress reads the OpenAI key from an environment variable named OPENAI_API_KEY first, from a PHP constant of the same name next and from the database last. We confirmed that order in the core files of our test site. The first two keep the key out of your database backups.

Your plugin then asks for text. This code checks support first. It does nothing on a site with no provider:

$builder = wp_ai_client_prompt( 'Write a haiku about WordPress.' );

if ( ! $builder->is_supported_for_text_generation() ) {
	return; // No provider is set up on this site.
}

$text = $builder->generate_text();

if ( is_wp_error( $text ) ) {
	return;
}

echo esc_html( $text );

On our test site with no provider plugin installed, the support check returned false and a direct generation call returned a WP_Error instead of text. We did not install the OpenAI provider plugin. We have not seen a live answer through this route.

This route adds no per-person limit and no spending cap for you. Anything that lets visitors trigger it still needs the checks in the next section.

How to Build a Safe WordPress AI Chatbot With Your Own Code

A safe WordPress AI chatbot keeps the OpenAI key on the server, checks every request, and limits how much one person can ask. You create the key, lock the endpoint, call the API, add the chat box, and test. It fits in one plugin file of about 160 lines.

OpenAI’s text generation guide says to use the Responses API over the older Chat Completions API for new apps. The sample plugin does that, and it answers with gpt-6-luna.

Step 1: Create the API Key and Store It in wp-config.php

Create the key in the OpenAI dashboard, and keep it out of themes, JavaScript, and the database. OpenAI’s production guide says to avoid exposing API keys in your code and to load them from environment variables or a secret manager. In WordPress, a constant in wp-config.php is the closest standard option.

Open the dashboard, create a key for this site, and set an expiry date if the form offers one. OpenAI recommends expiry dates and regular key rotation in that same guide.

Create an API key button in the OpenAI quickstart
Source: OpenAI developer quickstart from October 2026

Then add the key above the line that says “That’s all, stop editing” in wp-config.php:

define( 'SGC_OPENAI_KEY', 'paste-your-key-here' );

// Optional: let logged-out visitors use the chat. Leave it out to require a login.
// define( 'SGC_ALLOW_VISITORS', true );

Step 2: Lock the Endpoint With a Nonce and Limits

The endpoint is a REST route that checks a nonce, a capability, the question length, and two usage limits before it spends anything. The WordPress docs say a custom route needs a permission callback. They also warn that nonces should never be relied on for authentication, which is why the code checks both.

Create a folder named simple-gpt-chat in wp-content/plugins, and add a file named simple-gpt-chat.php. Start it with this block:

<?php
/**
 * Plugin Name: Simple GPT Chat
 * Description: A rate-limited chat box that calls the OpenAI Responses API from the server.
 * Version:     1.0.0
 */

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

const SGC_MODEL      = 'gpt-6-luna';
const SGC_MAX_CHARS  = 500;                    // Longest question we accept.
const SGC_USER_LIMIT = 10;                     // Questions per person per window.
const SGC_USER_TTL   = 10 * MINUTE_IN_SECONDS; // Length of that window.
const SGC_DAY_LIMIT  = 300;                    // Questions for the whole site per day.

add_action( 'rest_api_init', function () {
	register_rest_route( 'sgc/v1', '/ask', array(
		'methods'             => 'POST',
		'callback'            => 'sgc_ask',
		'permission_callback' => 'sgc_can_chat',
		'args'                => array(
			'question' => array(
				'required'          => true,
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_textarea_field',
			),
		),
	) );
} );

function sgc_can_chat( WP_REST_Request $request ) {
	// Nonce first: it proves the request came from a page on this site.
	if ( ! wp_verify_nonce( $request->get_header( 'X-WP-Nonce' ), 'wp_rest' ) ) {
		return new WP_Error( 'sgc_nonce', 'Reload the page and try again.', array( 'status' => 403 ) );
	}
	// Then the capability. Visitors are blocked unless you opt in.
	if ( is_user_logged_in() ) {
		return current_user_can( 'read' );
	}
	if ( defined( 'SGC_ALLOW_VISITORS' ) && SGC_ALLOW_VISITORS ) {
		return true;
	}
	return new WP_Error( 'sgc_login', 'Please log in to use the chat.', array( 'status' => 401 ) );
}

// One opaque ID per person. It also goes to OpenAI as the safety identifier.
function sgc_person_id() {
	$who = is_user_logged_in()
		? 'user-' . get_current_user_id()
		: 'ip-' . sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ?? '' ) );
	return substr( hash_hmac( 'sha256', $who, wp_salt() ), 0, 32 );
}

// Fixed-window counter. Returns false when the limit is used up.
function sgc_allow( $bucket, $limit, $ttl ) {
	$name = 'sgc_' . $bucket;
	$data = get_transient( $name );
	if ( ! is_array( $data ) ) {
		$data = array( 'n' => 0, 'until' => time() + $ttl );
	}
	if ( $data['n'] >= $limit ) {
		return false;
	}
	$data['n']++;
	set_transient( $name, $data, max( 1, $data['until'] - time() ) );
	return true;
}

Here is what each guard does:

  • Nonce: Proves the request came from a page on your own site, and blocks other sites from posting to your endpoint.
  • Capability: Allows logged-in users with the read capability. Visitors get through only if you set SGC_ALLOW_VISITORS.
  • Person limit: Ten questions per person every ten minutes, tracked with a hashed user ID or IP address in a transient.
  • Daily cap: 300 questions for the whole site per day. This is the ceiling on what the chat box can cost you.
Chat box page asking a logged-out visitor to log in

Warning: A nonce proves where a request came from. It says nothing about who sent it. If you allow visitors, the nonce is printed in the page for everyone. The limits are what protect you.

Note: A nonce lives between 12 and 24 hours by default. If a cache plugin serves a saved copy of the page for longer, the chat returns 403 until the cache refreshes. Exclude pages with the shortcode from page caching.

Six checks that run before OpenAI receives a question

Step 3: Call the Responses API From the Server

The server sends the question to the Responses API and reads the answer out of the response. It sends the key in an Authorization header, a question capped at 500 characters, and a limit of 400 output tokens. The browser never sees the key or the OpenAI address.

OpenAI’s reference describes max_output_tokens as an upper bound that includes reasoning tokens. It also says store defaults to true. The code sets it to false. The safety_identifier field takes a hashed ID for each user. The code supplies it.

Add this function below the first block:

function sgc_ask( WP_REST_Request $request ) {
	if ( ! defined( 'SGC_OPENAI_KEY' ) || '' === SGC_OPENAI_KEY ) {
		return new WP_Error( 'sgc_setup', 'Chat is not available right now.', array( 'status' => 503 ) );
	}

	$question = trim( $request->get_param( 'question' ) );
	$length   = mb_strlen( $question );
	if ( $length < 2 || $length > SGC_MAX_CHARS ) {
		return new WP_Error( 'sgc_length', 'Ask a question of 2 to ' . SGC_MAX_CHARS . ' characters.', array( 'status' => 400 ) );
	}

	$person = sgc_person_id();
	if ( ! sgc_allow( 'p_' . $person, SGC_USER_LIMIT, SGC_USER_TTL ) ) {
		return new WP_Error( 'sgc_limit', 'You have asked a lot of questions. Try again in a few minutes.', array( 'status' => 429 ) );
	}
	if ( ! sgc_allow( 'day_' . gmdate( 'Ymd' ), SGC_DAY_LIMIT, DAY_IN_SECONDS ) ) {
		return new WP_Error( 'sgc_daily', 'The chat has reached its limit for today.', array( 'status' => 429 ) );
	}

	$response = wp_remote_post( 'https://api.openai.com/v1/responses', array(
		'timeout' => 30,
		'headers' => array(
			'Authorization' => 'Bearer ' . SGC_OPENAI_KEY,
			'Content-Type'  => 'application/json',
		),
		'body'    => wp_json_encode( array(
			'model'             => SGC_MODEL,
			'instructions'      => 'You answer questions for visitors of ' . get_bloginfo( 'name' ) . '. Use three sentences or fewer. If you do not know, say so.',
			'input'             => $question,
			'max_output_tokens' => 400,
			'reasoning'         => array( 'effort' => 'low' ),
			'store'             => false,
			'safety_identifier' => $person,
		) ),
	) );

	$code = is_wp_error( $response ) ? 0 : wp_remote_retrieve_response_code( $response );
	if ( 200 !== $code ) {
		error_log( 'Simple GPT Chat: OpenAI request failed, status ' . $code ); // Never log the key.
		return new WP_Error( 'sgc_upstream', 'The assistant is busy. Try again soon.', array( 'status' => 503 ) );
	}

	$data = json_decode( wp_remote_retrieve_body( $response ), true );
	$text = '';
	foreach ( $data['output'] ?? array() as $item ) {
		if ( 'message' !== ( $item['type'] ?? '' ) ) {
			continue;
		}
		foreach ( $item['content'] ?? array() as $part ) {
			if ( 'output_text' === ( $part['type'] ?? '' ) ) {
				$text .= $part['text'];
			}
		}
	}
	if ( '' === $text ) {
		return new WP_Error( 'sgc_empty', 'No answer this time. Try rephrasing.', array( 'status' => 502 ) );
	}

	return rest_ensure_response( array( 'answer' => $text ) );
}

The loop in the middle matters. OpenAI’s guide warns that the output array often has more than one item. The text may not sit at the first position. The code walks every item and joins the text pieces.

OpenAI warning that the Responses API output array can hold several items
Source: OpenAI text generation guide from October 2026

Step 4: Add the Chat Box With a Shortcode

The shortcode prints a small form and one inline script only on pages that use it. The script posts the question to your endpoint with the nonce in a header. It writes the answer with textContent. Any HTML in a reply shows as plain text.

Add this block at the end of the file:

add_shortcode( 'simple_gpt_chat', function () {
	$can_see = is_user_logged_in() || ( defined( 'SGC_ALLOW_VISITORS' ) && SGC_ALLOW_VISITORS );
	if ( ! $can_see ) {
		return '<p><a href="' . esc_url( wp_login_url( get_permalink() ) ) . '">Log in</a> to use the chat.</p>';
	}

	$js = 'document.querySelectorAll("[data-sgc]").forEach(function(box){'
		. 'var form=box.querySelector("form"),out=box.querySelector("[data-sgc-out]");'
		. 'form.addEventListener("submit",function(e){e.preventDefault();'
		. 'var q=form.elements.question.value.trim();if(!q){return;}'
		. 'out.textContent="Thinking...";'
		. 'fetch(SGC.url,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":SGC.nonce},body:JSON.stringify({question:q})})'
		. '.then(function(r){return r.json();})'
		. '.then(function(d){out.textContent=d.answer||d.message||"Something went wrong.";})'
		. '.catch(function(){out.textContent="Network error. Try again.";});});});';

	wp_register_script( 'sgc-chat', false, array(), '1.0.0', true );
	wp_enqueue_script( 'sgc-chat' );
	wp_add_inline_script( 'sgc-chat', 'var SGC=' . wp_json_encode( array(
		'url'   => rest_url( 'sgc/v1/ask' ),
		'nonce' => wp_create_nonce( 'wp_rest' ),
	) ) . ';' . $js );

	return '<div data-sgc><form>'
		. '<p><label for="sgc-q" style="display:block">Ask a question</label>'
		. '<textarea id="sgc-q" name="question" maxlength="' . esc_attr( SGC_MAX_CHARS ) . '" rows="3" cols="50"></textarea></p>'
		. '<p><button type="submit">Send</button></p></form>'
		. '<p data-sgc-out role="status" aria-live="polite"></p></div>';
} );

Go to Plugins, activate Simple GPT Chat, and add [simple_gpt_chat] to a test page. Your plugin list should show it as active.

Simple GPT Chat plugin active on the WordPress Plugins screen
Chat box with a question field and a Send button on a WordPress page

Step 5: Test the Limits Before You Go Live

Test the failure paths first, because they decide whether your budget is safe. Ask 11 questions in a row, call the endpoint without a nonce, and open the page source to look for your key. A safe build blocks the 11th question, rejects the bare call, and shows no key.

We ran these checks on our test site, with a local stand-in for the OpenAI API and a placeholder key. The stand-in confirmed that the code sent the right headers, model, token limit, and hashed identifier.

Chat box showing a limit message after too many questions

Here is what we saw:

  • Missing nonce: The endpoint returned 403 for logged-in and logged-out calls without a valid nonce.
  • Visitors: With SGC_ALLOW_VISITORS off, a logged-out visitor saw a login link instead of the form.
  • Length: One-character and 501-character questions returned 400.
  • Person limit: The first 10 questions passed, and the 11th returned 429 with a plain message.
  • Daily cap: Once the daily counter reached 300, the next question returned 429.
  • Page source: The placeholder key did not appear anywhere in the page HTML for a logged-in user.
  • Missing key: With no key defined, the endpoint returned 503 and never called OpenAI.
  • OpenAI errors: A 429, a 503, and an empty answer from the stand-in each produced a friendly message and no raw error.
  • HTML in a reply: A reply containing an image tag with a script handler showed as plain text, and no script ran.

Tip: After going live, send one real test question with your own key and a low spending limit. We did not test live answers. Confirm the first reply and your usage dashboard yourself.

6 Mistakes That Let Strangers Spend Your OpenAI Budget

Most unsafe ChatGPT integrations share a few mistakes, and they all come down to letting an anonymous request spend your money. Older tutorials, including the earlier version of this guide, made several of them. Check your own code against this list before you publish.

  1. Public AJAX with no checks: A wp_ajax_nopriv_ action that calls OpenAI lets anyone on the internet run prompts on your key. Use a REST route with a permission callback, a nonce, and limits.
  2. A key in code or JavaScript: A key typed into a theme file, a snippet, or a script is readable by anyone who can see the file. Keep it in wp-config.php or an environment variable.
  3. No token limit: Without max_output_tokens, one question can produce a long and costly answer. Cap the output and cap the question length.
  4. No per-person or daily limit: A bot can send thousands of requests in an hour. A per-person limit and a site-wide daily cap turn a surprise bill into a known maximum.
  5. Trusting a nonce as a login: The WordPress docs warn against using nonces for authorization. Check a capability as well.
  6. Writing answers with innerHTML: A model reply can contain markup, and a visitor can try to steer it into producing some. Write replies with textContent.

Securing the chat box is one part of securing the site. Our WordPress security checklist covers the rest, and the WooCommerce security checklist adds store-specific checks.

How to Control Cost and Privacy After Launch

Watch your usage, set a hard spending limit, and tell visitors where their questions go. OpenAI’s spend limits guide says a hard spend limit makes affected API requests return a 429 error once the cap is reached. A spend alert only sends a notification while traffic continues.

Set an alert first and then a hard limit you can live with. Your plugin’s daily cap and OpenAI’s limit protect you in different places. Use both.

The sample code sets store to false and sends a hashed user ID instead of a name or email. That is a good default, but it does not make a chat box private. Add a line near the form that says questions are sent to OpenAI, and update your privacy policy.

Do not send order details, addresses, or other personal data in the prompt unless you have a reason and a legal basis. If you want other providers besides OpenAI, our guide to ChatGPT alternatives lists the main ones.

If you would rather hand this off, our team builds custom plugins and API integrations through our WordPress development services. We can add a chat box that follows the limits above to your theme.

Conclusion

You can integrate ChatGPT into WordPress in an afternoon, and the route you pick decides how safe it is. A plugin is quickest, the AI Client suits plugin builders, and custom code gives you the tightest control over cost.

Whatever you choose, use a current model such as gpt-6-luna, keep the key in wp-config.php, and limit how often people can ask. Add one more habit: test the limits before you publish.

Frequently Asked Questions (FAQs)

Q1. Can I add ChatGPT to WordPress for free?

The plugins and the AI Client are free to install, but each answer costs API usage. OpenAI bills by token. A small chat box can cost cents per month. Set a daily cap and a spend limit so it stays that way.

Q2. Do I need a ChatGPT Plus subscription to connect ChatGPT to WordPress?

No. A Plus subscription covers the ChatGPT app, and OpenAI’s help page lists API usage as billed separately. You need an API account with billing set up, and you create a key there.

Q3. Where should I store the OpenAI API key in WordPress?

Store it in a constant in wp-config.php or in an environment variable. Never put it in a theme file or in JavaScript. WordPress 7 reads OPENAI_API_KEY from the environment first and then from a constant. The database comes last. OpenAI’s production guide also recommends environment variables or a secret manager.

Q4. Can ChatGPT write a WordPress plugin for me?

It can draft one, but you must review it before you run it. Check the code against the six mistakes above, and test it on a staging site first. Many AI-written snippets copy the old public AJAX pattern, which is unsafe.

Q5. Will a chat box slow down my WordPress site?

The sample adds one small inline script and a short form, and only on pages that use the shortcode. The call to OpenAI happens after someone presses Send. On our test site the inline script was 725 bytes, and it did not appear on pages without the shortcode.

Q6. How do I stop visitors from running up my OpenAI bill?

Require a login, or limit visitors with a per-person cap and a daily site cap. Cap output tokens and question length too. Then set a hard spend limit in your OpenAI account, because a hard limit stops affected requests when it is reached.

Yash Kapoor
Yash Kapoor

Yash Kapoor is the founder and WordPress expert at DevDiggers, where he builds WordPress and WooCommerce plugins for loyalty programs, point-of-sale systems, digital wallets and affiliate management. He writes about developer tools, site performance and the technical side of running a WordPress store. He draws on years of building and maintaining production plugin codebases.

Leave a Reply

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