WordPress Plugin Guide
Create a WordPress plugin that adds AI-powered chatbots and monetizes conversations with sponsored content.
Plugin Features
- • AI-powered chat widget with shortcode support
- • Automatic moment detection and sponsored content display
- • WordPress admin panel for API key configuration
- • Event tracking for impressions and clicks
- • AJAX integration for seamless user experience
- • Responsive design that matches WordPress themes
Plugin Structure
momentize-wordpress/
├── momentize.php # Main plugin file
├── assets/
│ ├── momentize.js # Frontend JavaScript
│ └── momentize.css # Plugin styles
├── admin/
│ └── settings.php # Admin panel
└── readme.txt # WordPress plugin description1. Main Plugin File
Create the main plugin file with WordPress hooks and initialization:
ai-moments.php
<?php
/**
* Plugin Name: Momentize.ai - WordPress Integration
* Description: Monetize AI-powered features with intelligent moment detection and sponsored content
* Version: 1.0.0
* Author: Your Name
* Requires at least: 5.0
* Requires PHP: 7.4
* License: GPL v2 or later
*/
// Prevent direct access
if (!defined('ABSPATH')) {
exit;
}
// Define plugin constants
define('MOMENTIZE_PLUGIN_URL', plugin_dir_url(__FILE__));
define('MOMENTIZE_PLUGIN_PATH', plugin_dir_path(__FILE__));
define('MOMENTIZE_VERSION', '1.0.0');
// Initialize the plugin
class MomentizePlugin {
private $api_key;
private $api_url = 'http://localhost:8000';
public function __construct() {
add_action('init', array($this, 'init'));
add_action('admin_menu', array($this, 'add_admin_menu'));
add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
add_action('wp_ajax_momentize_analyze', array($this, 'ajax_analyze'));
add_action('wp_ajax_nopriv_momentize_analyze', array($this, 'ajax_analyze'));
add_action('wp_ajax_momentize_track_event', array($this, 'ajax_track_event'));
add_action('wp_ajax_nopriv_momentize_track_event', array($this, 'ajax_track_event'));
register_activation_hook(__FILE__, array($this, 'activate'));
register_deactivation_hook(__FILE__, array($this, 'deactivate'));
}
public function init() {
$this->api_key = get_option('momentize_api_key', '');
}
public function activate() {
add_option('momentize_api_key', '');
add_option('momentize_enabled', '1');
}
public function deactivate() {
// Clean up if needed
}
}
new MomentizePlugin();2. Admin Settings Panel
Add these methods to create a settings page in WordPress admin:
Admin Panel Methods
// Admin panel functionality
public function add_admin_menu() {
add_options_page(
'Momentize.ai Settings',
'Momentize.ai',
'manage_options',
'momentize-settings',
array($this, 'admin_page')
);
}
public function admin_page() {
if (isset($_POST['submit'])) {
update_option('momentize_api_key', sanitize_text_field($_POST['api_key']));
update_option('momentize_enabled', isset($_POST['enabled']) ? '1' : '0');
echo '<div class="notice notice-success"><p>Settings saved!</p></div>';
}
$api_key = get_option('momentize_api_key', '');
$enabled = get_option('momentize_enabled', '1');
?>
<div class="wrap">
<h1>Momentize.ai Settings</h1>
<form method="post" action="">
<table class="form-table">
<tr>
<th scope="row">API Key</th>
<td>
<input type="text" name="api_key" value="<?php echo esc_attr($api_key); ?>"
class="regular-text" required />
<p class="description">Get your API key from the Momentize.ai dashboard</p>
</td>
</tr>
<tr>
<th scope="row">Enable Momentize.ai</th>
<td>
<label>
<input type="checkbox" name="enabled" value="1"
<?php checked($enabled, '1'); ?> />
Enable sponsored content integration
</label>
</td>
</tr>
</table>
<?php submit_button(); ?>
</form>
<div class="card">
<h2>Usage Instructions</h2>
<p>Add the Momentize.ai chatbot to any page using this shortcode:</p>
<code>[momentize_chat]</code>
<p>Or integrate into existing AI features using JavaScript:</p>
<code>Momentize.analyze(conversation, sessionId)</code>
</div>
</div>
<?php
}3. AJAX Integration
Handle API communication through WordPress AJAX:
AJAX Handlers
// AJAX handlers for WordPress
public function enqueue_scripts() {
if (!get_option('momentize_enabled', '1')) {
return;
}
wp_enqueue_script(
'momentize-frontend',
MOMENTIZE_PLUGIN_URL . 'assets/momentize.js',
array('jquery'),
MOMENTIZE_VERSION,
true
);
wp_enqueue_style(
'momentize-styles',
MOMENTIZE_PLUGIN_URL . 'assets/momentize.css',
array(),
MOMENTIZE_VERSION
);
wp_localize_script('momentize-frontend', 'momentizeAjax', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('momentize_nonce')
));
}
public function ajax_analyze() {
check_ajax_referer('momentize_nonce', 'nonce');
$conversation = json_decode(stripslashes($_POST['conversation']), true);
$session_id = sanitize_text_field($_POST['session_id']);
if (empty($this->api_key)) {
wp_send_json_error('Momentize.ai API key not configured');
return;
}
$response = wp_remote_post($this->api_url . '/v1/analyze', array(
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $this->api_key
),
'body' => json_encode(array(
'conversation' => $conversation,
'session_id' => $session_id,
'user_context' => array(
'platform' => 'wordpress',
'url' => home_url()
)
)),
'timeout' => 30
));
if (is_wp_error($response)) {
wp_send_json_error('API request failed: ' . $response->get_error_message());
return;
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (wp_remote_retrieve_response_code($response) === 200) {
wp_send_json_success($data);
} else {
wp_send_json_error('API error: ' . ($data['detail'] ?? 'Unknown error'));
}
}
public function ajax_track_event() {
check_ajax_referer('momentize_nonce', 'nonce');
$event_data = array(
'event_type' => sanitize_text_field($_POST['event_type']),
'session_id' => sanitize_text_field($_POST['session_id']),
'impression_id' => sanitize_text_field($_POST['impression_id']),
'advertiser_id' => sanitize_text_field($_POST['advertiser_id']),
'metadata' => json_decode(stripslashes($_POST['metadata']), true)
);
$response = wp_remote_post($this->api_url . '/v1/events', array(
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $this->api_key
),
'body' => json_encode($event_data),
'timeout' => 10
));
if (is_wp_error($response)) {
wp_send_json_error('Event tracking failed');
return;
}
wp_send_json_success();
}4. Frontend JavaScript
Create the frontend interaction logic:
assets/ai-moments.js
// Frontend JavaScript integration
class MomentizeWP {
constructor() {
this.apiUrl = momentizeAjax.ajaxurl;
this.nonce = momentizeAjax.nonce;
this.sessionId = this.generateSessionId();
this.init();
}
init() {
// Auto-initialize if chat widget exists
const chatWidget = document.querySelector('.momentize-chat');
if (chatWidget) {
this.initChatWidget(chatWidget);
}
}
initChatWidget(widget) {
const chatContainer = widget.querySelector('.chat-messages');
const inputField = widget.querySelector('.chat-input');
const sendButton = widget.querySelector('.send-button');
let conversation = [];
sendButton.addEventListener('click', async () => {
const message = inputField.value.trim();
if (!message) return;
// Add user message to conversation
conversation.push({ role: 'user', content: message });
this.addMessageToUI(chatContainer, 'user', message);
inputField.value = '';
// Get AI response (simulate or integrate with your AI)
const aiResponse = await this.getAIResponse(message);
conversation.push({ role: 'assistant', content: aiResponse });
this.addMessageToUI(chatContainer, 'assistant', aiResponse);
// Analyze conversation for moments
this.analyzeConversation(conversation, chatContainer);
});
}
async analyzeConversation(conversation, container) {
try {
const response = await fetch(this.apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
action: 'momentize_analyze',
nonce: this.nonce,
conversation: JSON.stringify(conversation),
session_id: this.sessionId
})
});
const data = await response.json();
if (data.success && data.data.sponsored_content?.length > 0) {
this.displaySponsoredContent(container, data.data.sponsored_content);
}
} catch (error) {
console.error('Momentize.ai analysis error:', error);
}
}
displaySponsoredContent(container, ads) {
ads.forEach(ad => {
const adElement = this.createAdElement(ad);
container.appendChild(adElement);
// Track impression
this.trackEvent('impression', ad.impression_id, ad.advertiser_id);
});
}
createAdElement(ad) {
const adContainer = document.createElement('div');
adContainer.className = 'momentize-sponsored-message';
adContainer.innerHTML = `
<div class="sponsored-content-block">
<div class="disclosure">${ad.disclosure}</div>
<div class="content">
<h4 class="title">${ad.title}</h4>
<p class="description">${ad.description}</p>
<a href="${ad.cta_url}" target="_blank" class="cta-button"
data-impression-id="${ad.impression_id}"
data-advertiser-id="${ad.advertiser_id}">
${ad.cta_text}
</a>
</div>
</div>
`;
// Add click tracking
adContainer.querySelector('.cta-button').addEventListener('click', () => {
this.trackEvent('click', ad.impression_id, ad.advertiser_id);
});
return adContainer;
}
async trackEvent(eventType, impressionId, advertiserId) {
try {
await fetch(this.apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
action: 'momentize_track_event',
nonce: this.nonce,
event_type: eventType,
session_id: this.sessionId,
impression_id: impressionId,
advertiser_id: advertiserId,
metadata: JSON.stringify({
url: window.location.href,
referrer: document.referrer
})
})
});
} catch (error) {
console.error('Event tracking error:', error);
}
}
generateSessionId() {
return 'wp_session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
}
async getAIResponse(message) {
// Integrate with your AI service here
// For demo purposes, return a simple response
return "I understand you're looking for information about " + message + ". How can I help you further?";
}
addMessageToUI(container, role, content) {
const messageEl = document.createElement('div');
messageEl.className = `message ${role}-message`;
messageEl.innerHTML = `
<div class="message-content">${content}</div>
`;
container.appendChild(messageEl);
container.scrollTop = container.scrollHeight;
}
}
// Initialize when document is ready
document.addEventListener('DOMContentLoaded', () => {
new MomentizeWP();
});5. Chat Widget Shortcode
Add a shortcode to easily embed the chat widget:
Shortcode Implementation
// Shortcode for chat widget
add_shortcode('momentize_chat', array($this, 'chat_shortcode'));
public function chat_shortcode($atts) {
$atts = shortcode_atts(array(
'height' => '400px',
'placeholder' => 'Ask me anything...',
'title' => 'AI Assistant'
), $atts);
if (!get_option('momentize_enabled', '1')) {
return '<p>Momentize.ai is currently disabled.</p>';
}
ob_start();
?>
<div class="momentize-chat" style="height: <?php echo esc_attr($atts['height']); ?>">
<div class="chat-header">
<h3><?php echo esc_html($atts['title']); ?></h3>
</div>
<div class="chat-messages"></div>
<div class="chat-input-container">
<input type="text" class="chat-input" placeholder="<?php echo esc_attr($atts['placeholder']); ?>" />
<button class="send-button">Send</button>
</div>
</div>
<?php
return ob_get_clean();
}6. Plugin Styles
Style the chat widget and sponsored content:
assets/ai-moments.css
/* Plugin CSS - assets/momentize.css */
.momentize-chat {
border: 1px solid #ddd;
border-radius: 8px;
overflow: hidden;
background: #fff;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}
.chat-header {
background: #f8f9fa;
padding: 15px;
border-bottom: 1px solid #eee;
}
.chat-header h3 {
margin: 0;
font-size: 16px;
color: #333;
}
.chat-messages {
height: 300px;
overflow-y: auto;
padding: 15px;
}
.message {
margin-bottom: 15px;
display: flex;
}
.user-message {
justify-content: flex-end;
}
.assistant-message {
justify-content: flex-start;
}
.message-content {
max-width: 70%;
padding: 10px 15px;
border-radius: 18px;
font-size: 14px;
line-height: 1.4;
}
.user-message .message-content {
background: #007cba;
color: white;
}
.assistant-message .message-content {
background: #f1f1f1;
color: #333;
}
.chat-input-container {
padding: 15px;
border-top: 1px solid #eee;
display: flex;
gap: 10px;
}
.chat-input {
flex: 1;
padding: 10px 15px;
border: 1px solid #ddd;
border-radius: 20px;
outline: none;
font-size: 14px;
}
.send-button {
background: #007cba;
color: white;
border: none;
padding: 10px 20px;
border-radius: 20px;
cursor: pointer;
font-size: 14px;
}
.send-button:hover {
background: #005a87;
}
/* Sponsored content styling */
.momentize-sponsored-message {
margin: 15px 0;
border-left: 4px solid #007cba;
}
.sponsored-content-block {
background: #f8f9fa;
border-radius: 8px;
padding: 15px;
margin-left: 10px;
}
.disclosure {
font-size: 11px;
color: #666;
text-transform: uppercase;
font-weight: 600;
margin-bottom: 8px;
letter-spacing: 0.5px;
}
.title {
font-size: 16px;
font-weight: 600;
color: #333;
margin: 0 0 8px 0;
}
.description {
font-size: 14px;
color: #666;
margin: 0 0 12px 0;
line-height: 1.4;
}
.cta-button {
display: inline-block;
background: #007cba;
color: white;
padding: 8px 16px;
border-radius: 4px;
text-decoration: none;
font-size: 14px;
font-weight: 500;
transition: background-color 0.2s;
}
.cta-button:hover {
background: #005a87;
text-decoration: none;
color: white;
}Installation & Testing
Local Installation
- 1. Create the plugin directory in
/wp-content/plugins/ - 2. Add all the files with the code above
- 3. Go to WordPress Admin → Plugins and activate "Momentize.ai"
- 4. Navigate to Settings → Momentize.ai to configure your API key
Usage
Add Chat Widget to Pages
Use the shortcode in any post or page:
[momentize_chat]Customization Options
[momentize_chat height="500px" title="Customer Support" placeholder="How can we help?"]Testing
- 1. Add the shortcode to a test page
- 2. Start a conversation with purchase intent
- 3. Verify sponsored content appears after AI responses
- 4. Test click tracking in browser developer tools
Advanced Features
Integration with Existing AI Services
Replace the mock getAIResponse() function with real AI service integration:
OpenAI GPT
Use OpenAI's API for responses
WooCommerce
Product recommendation chatbot
Analytics Dashboard
Add a dashboard to show plugin performance:
- • Total conversations handled
- • Moments detected by type
- • Click-through rates
- • Revenue generated
Customization Options
- • Theme compatibility settings
- • Custom CSS override options
- • Ad frequency controls
- • User role restrictions
WordPress.org Submission
To publish your plugin to the WordPress.org repository:
- 1. Create a detailed
readme.txtfile - 2. Add plugin screenshots to
/assets/directory - 3. Test with WordPress Plugin Check plugin
- 4. Submit to WordPress.org for review
Review Guidelines
- • Follow WordPress coding standards
- • Sanitize and validate all user input
- • Use WordPress nonces for security
- • Include proper documentation
- • Test with latest WordPress version