Hooks and Filters Reference
This document provides comprehensive documentation of all WordPress hooks and filters used and provided by WooAI Chatbot Pro. Understanding these extension points enables developers to customize plugin behavior, integrate with external systems, and build custom functionality.
1. WordPress Hooks Used
WooAI Chatbot Pro integrates with core WordPress hooks for initialization, admin functionality, and frontend rendering.
plugins_loaded
Initializes the plugin after all plugins are loaded. This is the primary entry point.
// includes/class-plugin.php
add_action( 'plugins_loaded', 'woo_ai_chatbot_init' );
// i18n initialization
$this->loader->add_action( 'plugins_loaded', $i18n, 'load_plugin_textdomain' );
Hook into this to:
- Verify plugin dependencies before initialization
- Modify plugin behavior early in the lifecycle
add_action( 'plugins_loaded', function() {
// Check if WooAI Chatbot is active
if ( class_exists( 'WooAIChatbot\Plugin' ) ) {
// Your initialization code
}
}, 20 ); // Priority 20 runs after plugin init (priority 10)
admin_menu
Registers the plugin's admin menu pages.
$this->loader->add_action( 'admin_menu', $admin, 'add_admin_menu' );
Parameters: None
admin_init
Registers plugin settings with the WordPress Settings API.
$this->loader->add_action( 'admin_init', $settings, 'register_settings' );
Use case: Register additional settings fields or modify existing settings.
admin_notices
Displays admin notifications for license status and RAG system health.
$this->loader->add_action( 'admin_notices', $admin, 'display_rag_status_notices' );
$this->loader->add_action( 'admin_notices', $admin, 'display_license_notices' );
admin_enqueue_scripts
Enqueues admin JavaScript and CSS assets.
$this->loader->add_action( 'admin_enqueue_scripts', $admin, 'enqueue_scripts' );
Hook Priority: 10 (default)
wp_enqueue_scripts
Enqueues frontend widget assets (JavaScript, CSS, translations).
$this->loader->add_action( 'wp_enqueue_scripts', $widget, 'enqueue_scripts' );
$this->loader->add_action( 'wp_enqueue_scripts', $analytics, 'enqueue_tracking_script' );
wp_footer
Renders the chat widget markup in the footer.
$this->loader->add_action( 'wp_footer', $widget, 'render_widget' );
Conditional rendering: Widget rendering respects page exclusions, device settings, and display filters.
wp_head
Injects analytics tracking code (GA4, Meta Pixel, Mixpanel).
add_action( 'wp_head', array( $this, 'inject_tracking_code' ), 1 );
Priority: 1 (early injection for accurate tracking)
rest_api_init
Registers all REST API endpoints for the plugin.
$this->loader->add_action( 'rest_api_init', $chat_api, 'register_routes' );
$this->loader->add_action( 'rest_api_init', $settings, 'register_rest_routes' );
$this->loader->add_action( 'rest_api_init', $analytics_api, 'register_routes' );
$this->loader->add_action( 'rest_api_init', $playbooks_api, 'register_routes' );
$this->loader->add_action( 'rest_api_init', $topics_api, 'register_routes' );
$this->loader->add_action( 'rest_api_init', $rag_api, 'register_routes' );
$this->loader->add_action( 'rest_api_init', $promotion_api, 'register_routes' );
$this->loader->add_action( 'rest_api_init', $license_api, 'register_routes' );
REST Namespace: woo-ai-chatbot/v1
2. WooCommerce Hooks Used
The plugin leverages WooCommerce hooks for product indexing and user behavior tracking.
woocommerce_update_product / woocommerce_new_product
Triggers automatic product indexing when products are created or updated.
$this->loader->add_action( 'woocommerce_update_product', $this, 'index_product_on_save', 10, 1 );
$this->loader->add_action( 'woocommerce_new_product', $this, 'index_product_on_save', 10, 1 );
Parameters:
$product_id(int) - The product ID being saved
Behavior: Schedules background indexing via woo_ai_chatbot_index_product cron event.
woocommerce_delete_product
Removes deleted products from the vector index.
add_action( 'woocommerce_delete_product', array( $this, 'hook_delete_product_index' ), 10, 1 );
woocommerce_before_single_product
Tracks product page views for AI context enrichment.
add_action( 'woocommerce_before_single_product', array( $this, 'track_product_view' ), 10 );
Logged Event: product_view with product details and referrer
woocommerce_add_to_cart
Tracks when users add products to their cart.
add_action( 'woocommerce_add_to_cart', array( $this, 'track_cart_add' ), 10, 6 );
Parameters:
$cart_item_key(string) - Cart item key$product_id(int) - Product ID$quantity(int) - Quantity added$variation_id(int) - Variation ID (0 if simple product)$variation(array) - Variation attributes$cart_item_data(array) - Additional cart item data
woocommerce_cart_item_removed
Tracks cart item removals for abandoned cart analysis.
add_action( 'woocommerce_cart_item_removed', array( $this, 'track_cart_remove' ), 10, 2 );
woocommerce_before_checkout_form
Tracks checkout initiation for conversion funnel analysis.
add_action( 'woocommerce_before_checkout_form', array( $this, 'track_checkout_start' ), 10 );
woocommerce_thankyou
Tracks completed purchases with order details.
add_action( 'woocommerce_thankyou', array( $this, 'track_purchase' ), 10, 1 );
Parameters:
$order_id(int) - The completed order ID
pre_get_posts
Intercepts product search queries to track search behavior.
add_action( 'pre_get_posts', array( $this, 'track_product_search' ), 10, 1 );
Parameters:
$query(WP_Query) - The query object
3. Custom Actions Provided
These do_action() hooks allow developers to extend plugin functionality at key execution points.
woo_ai_chatbot_rtl_detected
Fires when an RTL (Right-to-Left) language is detected during plugin initialization.
do_action( 'woo_ai_chatbot_rtl_detected' );
Use case: Load RTL-specific stylesheets or modify UI behavior.
add_action( 'woo_ai_chatbot_rtl_detected', function() {
// Load RTL stylesheet
wp_enqueue_style(
'woo-ai-chatbot-rtl',
plugin_dir_url( __FILE__ ) . 'assets/css/rtl.css',
array( 'woo-ai-chatbot' ),
'1.0.0'
);
// Add RTL body class
add_filter( 'body_class', function( $classes ) {
$classes[] = 'woo-ai-chatbot-rtl';
return $classes;
});
});
woo_ai_product_search
Fires after a product search is executed, useful for analytics and debugging.
do_action( 'woo_ai_product_search', $search_term, $search_method, count( $products ) );
Parameters:
$search_term(string) - The search query$search_method(string) - Search method used (semantic,keyword,hybrid)$count(int) - Number of results returned
Example:
add_action( 'woo_ai_product_search', function( $term, $method, $count ) {
// Log to external analytics
error_log( sprintf(
'WooAI Search: "%s" via %s returned %d results',
$term,
$method,
$count
));
// Track in custom analytics
if ( class_exists( 'My_Analytics' ) ) {
My_Analytics::track( 'chatbot_search', [
'query' => $term,
'method' => $method,
'results' => $count,
]);
}
}, 10, 3 );
4. Custom Filters Provided
These apply_filters() hooks allow modification of plugin data and behavior.
woo_ai_chatbot_should_display
Controls widget visibility on the frontend.
$should_display = apply_filters( 'woo_ai_chatbot_should_display', true );
Parameters:
$should_display(bool) - Whether widget should render
Return: bool
Example:
add_filter( 'woo_ai_chatbot_should_display', function( $display ) {
// Hide on specific product categories
if ( is_product() ) {
global $product;
if ( has_term( 'restricted', 'product_cat', $product->get_id() ) ) {
return false;
}
}
// Hide for specific user roles
if ( current_user_can( 'administrator' ) ) {
return false; // Admins use direct support
}
return $display;
});
woo_ai_chatbot_format_response
Modifies the formatted response before returning to the frontend.
$response = apply_filters( 'woo_ai_chatbot_format_response', $response, $ai_response, $intent );
Parameters:
$response(array) - Formatted response withtext,type,data,quickReplies$ai_response(array) - Raw AI response$intent(string) - Detected intent (product_search,cart_help, etc.)
Return: array
Example:
add_filter( 'woo_ai_chatbot_format_response', function( $response, $ai_response, $intent ) {
// Add custom branding to all responses
$response['data']['branding'] = [
'logo' => get_site_icon_url(),
'name' => get_bloginfo( 'name' ),
];
// Add promotion banner for product searches
if ( $intent === 'product_search' ) {
$response['data']['promotion'] = [
'text' => 'Free shipping on orders over $50!',
'code' => 'FREESHIP50',
];
}
return $response;
}, 10, 3 );
woo_ai_chatbot_quick_replies
Customizes quick reply suggestions based on intent.
$quick_replies = apply_filters( 'woo_ai_chatbot_quick_replies', $quick_replies, $intent );
Parameters:
$quick_replies(array) - Array of['label' => string, 'value' => string]$intent(string) - Detected intent
Return: array
Example:
add_filter( 'woo_ai_chatbot_quick_replies', function( $replies, $intent ) {
// Add custom quick replies for product search
if ( $intent === 'product_search' ) {
$replies[] = [
'label' => __( 'View all on sale', 'my-plugin' ),
'value' => 'show_sale_products',
];
$replies[] = [
'label' => __( 'New arrivals', 'my-plugin' ),
'value' => 'show_new_arrivals',
];
}
return $replies;
}, 10, 2 );
woo_ai_chatbot_topics
Modifies available topic definitions for the topic detector.
$topics = apply_filters( 'woo_ai_chatbot_topics', $topics );
Parameters:
$topics(array) - Associative array of topic definitions
Return: array
Example:
add_filter( 'woo_ai_chatbot_topics', function( $topics ) {
// Add custom topic for warranty inquiries
$topics['warranty'] = [
'slug' => 'warranty',
'name' => 'Warranty Support',
'keywords' => ['warranty', 'guarantee', 'repair', 'broken', 'defect'],
'patterns' => ['/warranty\s+(claim|policy|period)/i'],
'priority' => 80,
'handler' => 'WarrantyHandler',
'description' => 'Product warranty and repair inquiries',
];
return $topics;
});
woo_ai_chatbot_detected_topics
Modifies topic detection results before they are used for routing.
$result = apply_filters( 'woo_ai_chatbot_detected_topics', $result, $message, $context );
Parameters:
$result(array) - Detection result withprimary,secondary,confidence,keywords_matched$message(string) - Original user message$context(array) - Session context
Return: array
Example:
add_filter( 'woo_ai_chatbot_detected_topics', function( $result, $message, $context ) {
// Override topic based on user segment
$user_id = get_current_user_id();
if ( $user_id && get_user_meta( $user_id, 'vip_customer', true ) ) {
// VIP customers always get priority support topic
if ( $result['confidence'] < 0.5 ) {
$result['primary'] = 'vip_support';
$result['confidence'] = 0.9;
}
}
return $result;
}, 10, 3 );
woo_ai_chatbot_trending_topics
Filters trending topic statistics for analytics display.
$topic_stats = apply_filters( 'woo_ai_chatbot_trending_topics', $topic_stats, $days );
Parameters:
$topic_stats(array) - Topic usage statistics$days(int) - Number of days analyzed
Return: array
woo_ai_chatbot_topic_handlers
Registers custom handlers for topic routing.
$handlers = apply_filters( 'woo_ai_chatbot_topic_handlers', $handlers );
Parameters:
$handlers(array) - Handler class mappings['topic_slug' => 'HandlerClass']
Return: array
Example:
add_filter( 'woo_ai_chatbot_topic_handlers', function( $handlers ) {
$handlers['warranty'] = 'MyPlugin\Handlers\WarrantyHandler';
$handlers['appointments'] = 'MyPlugin\Handlers\AppointmentHandler';
return $handlers;
});
woo_ai_chatbot_match_playbook
Overrides or modifies playbook matching logic.
$playbook = apply_filters( 'woo_ai_chatbot_match_playbook', $best_match, $message, $context );
Parameters:
$best_match(array|null) - Matched playbook or null$message(string) - User message$context(array) - Session context
Return: array|null
Example:
add_filter( 'woo_ai_chatbot_match_playbook', function( $playbook, $message, $context ) {
// Force specific playbook for returning customers
if ( is_user_logged_in() && empty( $playbook ) ) {
$order_count = wc_get_customer_order_count( get_current_user_id() );
if ( $order_count > 5 && stripos( $message, 'help' ) !== false ) {
// Return VIP support playbook for loyal customers
return [
'slug' => 'vip_support',
'name' => 'VIP Customer Support',
'priority' => 100,
];
}
}
return $playbook;
}, 10, 3 );
woo_ai_chatbot_playbook_response
Modifies playbook execution responses.
$response = apply_filters( 'woo_ai_chatbot_playbook_response', $response, $playbook, $context );
Parameters:
$response(array) - Playbook response withtext,type,quickReplies$playbook(array) - Executed playbook data$context(array) - Session context
Return: array
Example:
add_filter( 'woo_ai_chatbot_playbook_response', function( $response, $playbook, $context ) {
// Add playbook tracking data
$response['data']['playbook_id'] = $playbook['slug'];
$response['data']['step'] = $context['current_step'] ?? 0;
// Add escalation option for support playbooks
if ( strpos( $playbook['slug'], 'support' ) !== false ) {
$response['quickReplies'][] = [
'label' => __( 'Talk to human', 'my-plugin' ),
'value' => 'escalate_to_human',
];
}
return $response;
}, 10, 3 );
woo_ai_chatbot_shipping_info
Customizes the shipping information response.
$message = apply_filters( 'woo_ai_chatbot_shipping_info', $message );
Parameters:
$message(string) - Default shipping message
Return: string
Example:
add_filter( 'woo_ai_chatbot_shipping_info', function( $message ) {
return sprintf(
__( 'We ship worldwide! Standard delivery: 5-7 days ($%d). Express: 2-3 days ($%d). Free shipping on orders over $%d.', 'my-store' ),
8,
25,
75
);
});
woo_ai_chatbot_return_policy
Customizes the return policy response.
$message = apply_filters( 'woo_ai_chatbot_return_policy', $message );
Parameters:
$message(string) - Default return policy message
Return: string
Example:
add_filter( 'woo_ai_chatbot_return_policy', function( $message ) {
$policy_page = get_permalink( wc_get_page_id( 'refund_returns' ) );
return sprintf(
__( '30-day hassle-free returns. Items must be unworn with tags. View full policy: %s', 'my-store' ),
$policy_page
);
});
waa_search_results_before_boost / waa_search_results_after_boost
Modifies search results before and after promotion boost is applied.
$results = apply_filters( 'waa_search_results_before_boost', $results, $query );
// ... promotion boost applied ...
$results = apply_filters( 'waa_search_results_after_boost', $results, $query );
Parameters:
$results(array) - Search results withproduct_id,similarity, metadata$query(string) - Search query
Return: array
Example:
// Exclude out-of-stock products before boosting
add_filter( 'waa_search_results_before_boost', function( $results, $query ) {
return array_filter( $results, function( $item ) {
$product = wc_get_product( $item['product_id'] );
return $product && $product->is_in_stock();
});
}, 10, 2 );
// Add custom scoring after boost
add_filter( 'waa_search_results_after_boost', function( $results, $query ) {
foreach ( $results as &$item ) {
$product = wc_get_product( $item['product_id'] );
if ( $product && $product->is_on_sale() ) {
$item['similarity'] *= 1.1; // 10% boost for sale items
$item['on_sale'] = true;
}
}
return $results;
}, 10, 2 );
5. Cron Jobs
The plugin schedules several background tasks via WordPress cron.
woo_ai_chatbot_daily_index
Runs daily to index all products for semantic search.
// Scheduled on plugin activation
if ( ! wp_next_scheduled( 'woo_ai_chatbot_daily_index' ) ) {
wp_schedule_event( time(), 'daily', 'woo_ai_chatbot_daily_index' );
}
// Handler
add_action( 'woo_ai_chatbot_daily_index', [ $plugin, 'run_daily_indexing' ] );
Frequency: Daily
woo_ai_chatbot_index_product
Indexes a single product (triggered after product save).
wp_schedule_single_event( time() + 10, 'woo_ai_chatbot_index_product', [ $product_id ] );
Parameters:
$product_id(int) - Product ID to index
Delay: 10 seconds after product save
woo_ai_chatbot_cleanup
Performs weekly maintenance tasks (old session cleanup, log rotation).
if ( ! wp_next_scheduled( 'woo_ai_chatbot_cleanup' ) ) {
wp_schedule_event( time(), 'weekly', 'woo_ai_chatbot_cleanup' );
}
Frequency: Weekly
woo_ai_chatbot_batch_index
Indexes products in batches for large catalogs.
add_action( 'woo_ai_chatbot_batch_index', [ $plugin, 'run_batch_index' ], 10, 2 );
Parameters:
$offset(int) - Starting offset$limit(int) - Batch size
waa_cleanup_playbook_sessions
Cleans up expired playbook sessions.
if ( ! wp_next_scheduled( 'waa_cleanup_playbook_sessions' ) ) {
wp_schedule_event( time(), 'hourly', 'waa_cleanup_playbook_sessions' );
}
Frequency: Hourly
woo_ai_supabase_keepalive
Prevents Supabase free tier from pausing due to inactivity.
if ( ! wp_next_scheduled( 'woo_ai_supabase_keepalive' ) ) {
wp_schedule_event( time(), 'daily', 'woo_ai_supabase_keepalive' );
}
Frequency: Daily
6. Extension Examples
Adding a Custom AI Tool
Create a custom tool that the AI can invoke during conversations:
/**
* Register custom AI tool for appointment booking
*/
add_filter( 'woo_ai_chatbot_ai_tools', function( $tools ) {
$tools['book_appointment'] = [
'name' => 'book_appointment',
'description' => 'Books a consultation appointment for the customer',
'parameters' => [
'date' => [
'type' => 'string',
'description' => 'Preferred date (YYYY-MM-DD format)',
'required' => true,
],
'time' => [
'type' => 'string',
'description' => 'Preferred time slot',
'required' => true,
],
'service' => [
'type' => 'string',
'description' => 'Type of consultation',
'required' => false,
],
],
'handler' => 'MyPlugin\Tools\AppointmentTool::handle',
];
return $tools;
});
/**
* Tool handler class
*/
namespace MyPlugin\Tools;
class AppointmentTool {
public static function handle( $params, $context ) {
$date = sanitize_text_field( $params['date'] );
$time = sanitize_text_field( $params['time'] );
// Check availability
$available = self::check_availability( $date, $time );
if ( ! $available ) {
return [
'success' => false,
'message' => sprintf(
__( 'Sorry, %s at %s is not available. Would you like me to suggest alternatives?', 'my-plugin' ),
$date,
$time
),
];
}
// Book the appointment
$booking_id = self::create_booking( $date, $time, $context['session_id'] );
return [
'success' => true,
'booking_id' => $booking_id,
'message' => sprintf(
__( 'Great! I\'ve booked your consultation for %s at %s. Confirmation #%s', 'my-plugin' ),
$date,
$time,
$booking_id
),
];
}
}
Modifying Chat Context
Inject custom data into the AI context for enhanced responses:
/**
* Add customer loyalty data to chat context
*/
add_filter( 'woo_ai_chatbot_session_context', function( $context, $session_id ) {
$user_id = get_current_user_id();
if ( $user_id ) {
// Add loyalty tier
$context['customer'] = [
'id' => $user_id,
'loyalty_tier' => get_user_meta( $user_id, 'loyalty_tier', true ) ?: 'standard',
'total_spent' => wc_get_customer_total_spent( $user_id ),
'order_count' => wc_get_customer_order_count( $user_id ),
'member_since' => get_userdata( $user_id )->user_registered,
];
// Add recent orders
$orders = wc_get_orders([
'customer_id' => $user_id,
'limit' => 3,
'orderby' => 'date',
'order' => 'DESC',
]);
$context['recent_orders'] = array_map( function( $order ) {
return [
'id' => $order->get_id(),
'date' => $order->get_date_created()->format( 'Y-m-d' ),
'status' => $order->get_status(),
'total' => $order->get_total(),
];
}, $orders );
}
return $context;
}, 10, 2 );
Adding a Custom Playbook Step
Create custom step types for playbook automation:
/**
* Register custom playbook step type for sending emails
*/
add_filter( 'woo_ai_chatbot_playbook_step_types', function( $types ) {
$types['send_email'] = [
'name' => 'Send Email',
'description' => 'Sends an email to the customer or support team',
'handler' => 'MyPlugin\Playbook\EmailStep::execute',
'parameters' => [
'to' => [ 'type' => 'string', 'required' => true ],
'subject' => [ 'type' => 'string', 'required' => true ],
'template' => [ 'type' => 'string', 'required' => true ],
],
];
return $types;
});
/**
* Step handler
*/
namespace MyPlugin\Playbook;
class EmailStep {
public static function execute( $step, $context ) {
$to = self::resolve_recipient( $step['to'], $context );
$subject = self::replace_variables( $step['subject'], $context );
$body = self::render_template( $step['template'], $context );
$sent = wp_mail( $to, $subject, $body, [
'Content-Type: text/html; charset=UTF-8',
]);
return [
'success' => $sent,
'message' => $sent
? __( 'Email sent successfully!', 'my-plugin' )
: __( 'Failed to send email.', 'my-plugin' ),
'data' => [ 'email_sent' => $sent ],
];
}
}
Adding Custom Analytics Events
Track custom events in the chatbot analytics system:
/**
* Track custom events from playbook executions
*/
add_action( 'woo_ai_chatbot_playbook_step_completed', function( $playbook_slug, $step_index, $result, $context ) {
// Track in WooAI analytics
do_action( 'woo_ai_chatbot_track_event', 'playbook_step', [
'playbook' => $playbook_slug,
'step' => $step_index,
'success' => $result['success'] ?? false,
'session_id' => $context['session_id'],
]);
// Track in external analytics
if ( function_exists( 'gtag' ) ) {
wp_add_inline_script( 'google-gtag', sprintf(
"gtag('event', 'chatbot_playbook_step', %s);",
wp_json_encode([
'playbook_slug' => $playbook_slug,
'step_index' => $step_index,
'success' => $result['success'] ?? false,
])
));
}
}, 10, 4 );
/**
* Custom event tracking helper
*/
function woo_ai_track_custom_event( $event_name, $params = [] ) {
global $wpdb;
$wpdb->insert(
$wpdb->prefix . 'waa_events',
[
'session_id' => $params['session_id'] ?? '',
'event_type' => $event_name,
'event_data' => wp_json_encode( $params ),
'created_at' => current_time( 'mysql' ),
],
[ '%s', '%s', '%s', '%s' ]
);
}
Best Practices
- Priority Management: Use appropriate hook priorities to ensure your code runs at the right time
- Performance: Avoid expensive operations in frequently-called filters like
woo_ai_chatbot_format_response - Compatibility: Always check if the plugin is active before hooking into its filters
- Data Validation: Sanitize and validate all data in filter callbacks
- Documentation: Document custom hooks in your extension for other developers
// Always check plugin availability
if ( ! class_exists( 'WooAIChatbot\Plugin' ) ) {
return;
}
// Use namespaced functions to avoid conflicts
add_filter( 'woo_ai_chatbot_topics', 'MyPlugin\Topics\add_custom_topics' );
Version Compatibility
| Hook | Since Version | Notes |
|---|---|---|
woo_ai_chatbot_should_display |
0.1.0 | Core filter |
woo_ai_chatbot_format_response |
0.1.0 | Core filter |
woo_ai_chatbot_topics |
0.2.0 | Topic system |
woo_ai_chatbot_match_playbook |
0.3.0 | Playbook system |
waa_search_results_before_boost |
0.4.0 | Promotion boost |
woo_ai_supabase_keepalive |
0.4.5 | Supabase integration |
For additional support, refer to the Plugin Architecture documentation or contact the development team.