MxChat Developer Hooks & Filters

Two powerful WordPress filters to customize how your AI chatbot learns content and responds to visitors. Simple, flexible, and fully extensible.

MxChat developer workspace with PHP code editor and WordPress hooks illustration
1 WordPress Filter

mxchat_before_process_post

Modify a WordPress post's data right before MxChat indexes it into the knowledge base. This filter fires during knowledge base indexing — when you select posts, pages, or products to train your bot.

Arguments:

  • $post (WP_Post) — the full WordPress post object being processed
  • $bot_id (string) — which bot is being trained (e.g. 'default')

After your filter runs: MxChat extracts the post's title, excerpt, and content (plus WooCommerce data like price, SKU, and categories if applicable) and stores it in the knowledge base.

Example 1

Add custom field data to the knowledge base

Append product specifications or FAQs stored in custom fields so MxChat learns them:

add_filter('mxchat_before_process_post', function($post, $bot_id) { // Append custom field data so MxChat learns it $specs = get_post_meta($post->ID, 'product_specifications', true); if ($specs) { $post->post_content .= "\n\nSpecifications:\n" . $specs; } return $post; }, 10, 2);
Example 2

Exclude content from the knowledge base

Strip out internal notes or sensitive sections before indexing:

add_filter('mxchat_before_process_post', function($post, $bot_id) { // Remove [internal_note]...[/internal_note] blocks $post->post_content = preg_replace( '/[internal_note].*?[/internal_note]/s', '', $post->post_content ); return $post; }, 10, 2);
Diagram showing WordPress post object passing through the mxchat_before_process_post filter into the knowledge base
2 WordPress Filter

mxchat_system_instructions

Dynamically modify the system prompt sent to the AI before every response. Inject live data, customize bot behavior, or add conditional logic to your prompts.

Arguments:

  • $instructions (string) — the system prompt text (placeholders like {visitor_name} already replaced)
  • $bot_id (string) — which bot this is for
  • $session_id (string) — the current visitor's session ID

Processing order:

  • Bot Instructions
  • →
  • Fallback Default
  • →
  • URL Stripping
  • →
  • {visitor_name}
  • →
  • Your Filter
  • →
  • do_shortcode()
  • →
  • Sent to AI

Since do_shortcode() runs after the filter, you can insert shortcodes in your filter and they'll be processed automatically.

Example 1

Inject live data into the system prompt

Give the AI real-time awareness of business hours or stock status:

add_filter('mxchat_system_instructions', function($instructions, $bot_id, $session_id) { // Add current store hours for accurate answers $today = current_time('l'); $hours = get_option('store_hours_' . strtolower($today), 'Closed'); $instructions .= "nnToday is {$today}. Store hours: {$hours}."; return $instructions; }, 10, 3);
Example 2

Customize behavior per bot

Give different bots different personalities using the $bot_id argument:

add_filter('mxchat_system_instructions', function($instructions, $bot_id, $session_id) { if ($bot_id === 'sales') { $instructions .= "nnAlways suggest relevant products and include pricing."; } elseif ($bot_id === 'support') { $instructions .= "\n\nFocus on troubleshooting. Ask clarifying questions first."; } return $instructions; }, 10, 3);
Flowchart showing the MxChat system prompt processing pipeline from bot instructions through filters to AI
3 No PHP Required

Shortcode Support in System Prompts

You can type WordPress shortcodes directly into your system prompt field in MxChat settings — no PHP required. MxChat automatically expands them before sending the prompt to the AI.

How it works: do_shortcode() runs at the end of the processing pipeline, so any shortcode — whether added in settings or injected via the mxchat_system_instructions filter — gets fully expanded before reaching the AI.

Example: Add your return policy shortcode to the system prompt and MxChat will always have your latest policy text:

You are a helpful assistant for our store.

Our current return policy:
[return_policy]

MxChat will expand [return_policy] into your actual return policy text every time a visitor asks a question — ensuring the bot always has your latest content.

4 Added in MxChat 3.2.22

Hooks for add-ons and site integrations

MxChat 3.2.22 adds six filters, two browser events and one helper. They let an add-on or theme put a button in the chat toolbar, write to a chat transcript, shape what live agents read, and adjust the visitor address and the date line MxChat sends with every message.

Filter

mxchat_client_ip

Override the visitor address used for logged-out rate limiting and transcript identifiers. MxChat resolves the connecting address, or the address Cloudflare reports when the request arrives from a Cloudflare edge. Receives the resolved address and the raw REMOTE_ADDR. Return a valid IP address; anything else is ignored.

add_filter('mxchat_client_ip', function($ip, $remote) { // Site behind a trusted proxy that sets X-Real-IP $real = isset($_SERVER['HTTP_X_REAL_IP']) ? trim($_SERVER['HTTP_X_REAL_IP']) : ''; return filter_var($real, FILTER_VALIDATE_IP) ? $real : $ip; }, 10, 2);
Filter

mxchat_current_datetime_line

Reword or suppress the line that tells the model the current date and time in the site's timezone. MxChat sends it with every message, outside the cached instructions, so it never affects prompt caching. Receives the line and the bot ID. Return the text to send, or an empty string to send none.

add_filter('mxchat_current_datetime_line', function($line, $bot_id) { // The archive bot answers about past events only; send it no date line return $bot_id === 'archive' ? '' : $line; }, 10, 2);
Filter

mxchat_transcript_user_message

Change how a visitor message is recorded for humans without changing what the AI receives. Receives the message, the session ID and a context: transcript for the stored row or agent for the text relayed to a live agent in Telegram or Slack. Return the text to store or relay. The Forms add-on uses it to turn its wizard completion signal into a readable line.

add_filter('mxchat_transcript_user_message', function($message, $session_id, $context) { // Show humans a readable line instead of an internal token if (strpos($message, '[BOOKING_DONE]') === 0) { return 'Completed the booking wizard'; } return $message; }, 10, 3);
Filter

mxchat_ai_conversation_history

Filter the transcript rows about to become the model's conversation history. Receives the chronological entries (each with id, role, content, timestamp and agent_name) and the session ID. Drop or rewrite entries an add-on wrote for humans that the model already receives another way.

add_filter('mxchat_ai_conversation_history', function($history, $session_id) { // Keep rows written for humans out of the model's history return array_values(array_filter($history, function($row) { return strpos($row['content'], 'Completed the booking wizard') !== 0; })); }, 10, 2);
Filter

mxchat_chat_toolbar_items

Add a button to the chat toolbar from an add-on or a theme. Receives the current items and the bot ID. Return the array with your item added under a key, with html and an order. The markup is rendered with the page (buttons, spans and inline SVG icons are allowed) and only when the site's toolbar is switched on, so your code never has to check that setting or wait for the toolbar to appear. Open any panel the button controls from your script and append it to the body, not to the toolbar.

add_filter('mxchat_chat_toolbar_items', function($items, $bot_id) { if (is_admin()) { return $items; } $items['my-help'] = array( 'id' => 'my-help', 'html' => '<button type="button" class="toolbar-btn my-help-btn" title="Help" aria-label="Help">?</button>', 'order' => 20, ); return $items; }, 10, 2);
Browser events

mxchat:toolbar-ready and mxchat:opened

Two events on the document for scripts. mxchat:toolbar-ready fires once, after the toolbar has been shown or hidden according to the site's setting, with detail.enabled. mxchat:opened fires once per chatbot the first time its window is on screen, from the launcher, the pre-chat bubble, an embedded widget or another script, with detail.botId and detail.embedded. Use them to bind behaviour or make requests only when a visitor actually opens the chat instead of on every page view. Scripts that load late can read MxChatInstances.toolbarReady and call MxChatInstances.hasOpened(botId).

document.addEventListener('mxchat:toolbar-ready', function (e) { if (!e.detail.enabled) { return; } document.querySelectorAll('.my-help-btn').forEach(function (btn) { btn.addEventListener('click', openHelpPanel); }); }); document.addEventListener('mxchat:opened', function (e) { // Runs once per bot, the first time its window is shown fetch('/wp-json/my-plugin/v1/warm?bot=' + encodeURIComponent(e.detail.botId)); });
Filter

mxchat_handoff_card_sections

Add sections to the live agent handoff card sent to a Telegram topic or Slack channel. Receives the current sections, the session ID and the destination (telegram or slack). Return an array of sections, each with a title and a list of plain-text lines. Escaping for the destination is handled for you.

add_filter('mxchat_handoff_card_sections', function($sections, $session_id, $destination) { $sections[] = array( 'title' => 'Account', 'lines' => array('Plan: Pro', 'Renews: 1 December 2026'), ); return $sections; }, 10, 3);
Helper

MxChat_Utils::save_session_message

A static helper for add-ons that need to append a message to a chat transcript. Pass the session ID, the role (user, bot, system or agent) and the message; the new row ID is returned, or 0 when nothing was written. Guard the call with method_exists so your add-on keeps working on older MxChat versions.

if (method_exists('MxChat_Utils', 'save_session_message')) { MxChat_Utils::save_session_message($session_id, 'system', 'Completed the booking wizard'); }
Filter

mxchat_error_response

Added in MxChat 3.2.28. Replace the error message a chat visitor sees with your own wording. Receives the message, the error code and a context array with session_id, bot_id, streaming and provider. Codes include missing_session, empty_message, message_too_long, rate_limit_exceeded, banned_ip, banned_email, agent_send_failed, pdf_error, invalid_embedding, firewall_blocked, the embedding_* codes and provider codes such as openai_rate_limit and claude_api_error. The filter does not run for administrators, who keep the original message with the provider's reason. Links, bold, italics and line breaks are kept in your text, and the code sent with the response does not change.

add_filter('mxchat_error_response', function($message, $code, $context) { if ($code === 'rate_limit_exceeded') { return 'You have sent a lot of messages. Please try again in a few minutes.'; } return $message; }, 10, 3);
Filter

mxchat_pre_vector_query

Added in MxChat 3.2.28. Answer a classic Pinecone query from your own store, such as a cache or another vector database. Receives null, the query vector, the number of matches wanted and a context array with source, bot_id, namespace and the full query. Return null to send the query to Pinecone, or an array with a matches list in Pinecone's shape, each match holding id, score and metadata. Any other return counts as null. Your matches still pass the threshold and role checks, and the chunk text comes from your matches. Document indexes are not covered, because they do not use this query. A Pinecone host and key must still be configured for the query to run. For the main chatbot they come from the Pinecone settings, which you can supply with the WordPress filter option_mxchat_pinecone_addon_options; for a Multi-Bot bot, use mxchat_get_bot_pinecone_config.

add_filter('mxchat_pre_vector_query', function($results, $vector, $top_k, $context) { if ($context['source'] !== 'chat') { return $results; } return array('matches' => my_store_search($vector, $top_k, $context['namespace'])); }, 10, 4);
Filter

mxchat_pre_vector_store

Added in MxChat 3.2.29. The write-side companion of mxchat_pre_vector_query: store, list and delete knowledge base vectors in your own store instead of Pinecone. Receives null, the operation (upsert, delete or list_ids), a payload in Pinecone's shape and a context array with bot_id and namespace. For upsert the payload holds vectors (each with id, values and metadata) and namespace; for delete, ids and namespace; for list_ids, prefix and namespace. Return null to send the request to Pinecone. For upsert and delete, return true when your store handled it or a WP_Error when it failed; for list_ids, return an array of ids as strings or integers. Any other return counts as null, so a mistake in your code never loses a write silently. It covers imports, auto-sync, re-imports, deletions and the clean-up of old chunks. Document indexes are not covered, and the Knowledge screen's own Pinecone listings still read Pinecone directly. As with mxchat_pre_vector_query, Pinecone must be switched on with a host and key configured.

add_filter('mxchat_pre_vector_store', function($result, $op, $payload, $context) { if ($op === 'upsert') { return my_store_upsert($payload['vectors'], $context['namespace']) ? true : new WP_Error('my_store_failed', 'The vector could not be stored.'); } if ($op === 'delete') { my_store_delete($payload['ids'], $context['namespace']); return true; } if ($op === 'list_ids') { return my_store_ids_with_prefix($payload['prefix'], $context['namespace']); } return $result; }, 10, 4);
Filter

mxchat_product_index_prices

Added in MxChat 3.2.29. Change the WooCommerce prices MxChat writes into the knowledge base, before the price lines are built. Receives an array with regular_price, sale_price and price as stored in WooCommerce, and the product. Return the array with your values. An empty string for a key leaves its line out, just as an empty price does; a missing or non-scalar key keeps the stored value. It applies to product imports, auto-sync and re-imports, so re-import your products after adding it.

add_filter('mxchat_product_index_prices', function($prices, $product) { // Quote-only products are stored at 0; leave their price lines out if ((float) $product->get_price('edit') === 0.0) { return array('regular_price' => '', 'sale_price' => '', 'price' => ''); } return $prices; }, 10, 2);
Filter

mxchat_product_price_lines

Added in MxChat 3.2.29. Replace the finished price lines for a product, for example to say Price on request. Receives the lines as built (Price, Sale Price and Price Range, one per line), the product and the prices array after mxchat_product_index_prices. Return a string; anything else keeps the lines as built. Re-import your products after adding it.

add_filter('mxchat_product_price_lines', function($lines, $product, $prices) { if (has_term('quote-only', 'product_tag', $product->get_id())) { return "Price: Price on request\n"; } return $lines; }, 10, 3);

Start Customizing Your MxChat Bot

Use these hooks to make your AI chatbot smarter, more accurate, and perfectly tailored to your WordPress site. Copy the examples above and start building.

Purchase MxChat