מדריך Hooks ו-Filters

מדריך Hooks ו-Filters

מסמך זה מספק תיעוד מקיף של כל hooks ו-filters של WordPress בהם משתמש ומספק WooAI Chatbot Pro. הבנת נקודות הרחבה אלו מאפשרת למפתחים להתאים אישית את התנהגות התוסף, לשלב עם מערכות חיצוניות ולבנות פונקציונליות מותאמת.


1. Hooks של WordPress בשימוש

WooAI Chatbot Pro משתלב עם hooks ליבה של WordPress לאתחול, פונקציונליות מנהל ורינדור בצד לקוח.

plugins_loaded

מאתחל את התוסף לאחר שכל התוספים נטענו. זוהי נקודת הכניסה הראשית.

// includes/class-plugin.php
add_action( 'plugins_loaded', 'woo_ai_chatbot_init' );

// i18n initialization
$this->loader->add_action( 'plugins_loaded', $i18n, 'load_plugin_textdomain' );

השתמשו בזה כדי:
– לאמת תלויות תוסף לפני אתחול
– לשנות התנהגות תוסף מוקדם במחזור החיים

add_action( 'plugins_loaded', function() {
    // בדיקה אם WooAI Chatbot פעיל
    if ( class_exists( 'WooAIChatbotPlugin' ) ) {
        // קוד האתחול שלכם
    }
}, 20 ); // Priority 20 רץ אחרי אתחול התוסף (priority 10)

admin_menu

רושם את עמודי תפריט המנהל של התוסף.

$this->loader->add_action( 'admin_menu', $admin, 'add_admin_menu' );

פרמטרים: אין

admin_init

רושם הגדרות תוסף עם WordPress Settings API.

$this->loader->add_action( 'admin_init', $settings, 'register_settings' );

מקרה שימוש: רישום שדות הגדרות נוספים או שינוי הגדרות קיימות.

admin_notices

מציג התראות מנהל עבור סטטוס רישיון ובריאות מערכת RAG.

$this->loader->add_action( 'admin_notices', $admin, 'display_rag_status_notices' );
$this->loader->add_action( 'admin_notices', $admin, 'display_license_notices' );

admin_enqueue_scripts

טוען נכסי JavaScript ו-CSS של מנהל.

$this->loader->add_action( 'admin_enqueue_scripts', $admin, 'enqueue_scripts' );

Hook Priority: 10 (ברירת מחדל)

wp_enqueue_scripts

טוען נכסי widget בצד לקוח (JavaScript, CSS, תרגומים).

$this->loader->add_action( 'wp_enqueue_scripts', $widget, 'enqueue_scripts' );
$this->loader->add_action( 'wp_enqueue_scripts', $analytics, 'enqueue_tracking_script' );

מרנדר את markup של widget הצ’אט ב-footer.

$this->loader->add_action( 'wp_footer', $widget, 'render_widget' );

רינדור מותנה: רינדור Widget מכבד החרגות עמודים, הגדרות מכשיר ומסנני תצוגה.

מזריק קוד מעקב אנליטיקה (GA4, Meta Pixel, Mixpanel).

add_action( 'wp_head', array( $this, 'inject_tracking_code' ), 1 );

Priority: 1 (הזרקה מוקדמת למעקב מדויק)

rest_api_init

רושם את כל נקודות הקצה של REST API עבור התוסף.

$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. Hooks של WooCommerce בשימוש

התוסף ממנף hooks של WooCommerce לאינדוקס מוצרים ומעקב אחר התנהגות משתמש.

woocommerce_update_product / woocommerce_new_product

מפעיל אינדוקס מוצרים אוטומטי כאשר מוצרים נוצרים או מתעדכנים.

$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 );

פרמטרים:
$product_id (int) – מזהה המוצר שנשמר

התנהגות: מתזמן אינדוקס ברקע דרך אירוע cron woo_ai_chatbot_index_product.

woocommerce_delete_product

מסיר מוצרים שנמחקו מאינדקס הוקטורים.

add_action( 'woocommerce_delete_product', array( $this, 'hook_delete_product_index' ), 10, 1 );

woocommerce_before_single_product

עוקב אחר צפיות בדף מוצר להעשרת הקשר AI.

add_action( 'woocommerce_before_single_product', array( $this, 'track_product_view' ), 10 );

אירוע מתועד: product_view עם פרטי מוצר ומקור הפניה

woocommerce_add_to_cart

עוקב כאשר משתמשים מוסיפים מוצרים לעגלה.

add_action( 'woocommerce_add_to_cart', array( $this, 'track_cart_add' ), 10, 6 );

פרמטרים:
$cart_item_key (string) – מפתח פריט עגלה
$product_id (int) – מזהה מוצר
$quantity (int) – כמות שהתווספה
$variation_id (int) – מזהה וריאציה (0 אם מוצר פשוט)
$variation (array) – תכונות וריאציה
$cart_item_data (array) – נתוני פריט עגלה נוספים

woocommerce_cart_item_removed

עוקב אחר הסרות פריטים מעגלה לניתוח עגלות נטושות.

add_action( 'woocommerce_cart_item_removed', array( $this, 'track_cart_remove' ), 10, 2 );

woocommerce_before_checkout_form

עוקב אחר התחלת checkout לניתוח משפך המרה.

add_action( 'woocommerce_before_checkout_form', array( $this, 'track_checkout_start' ), 10 );

woocommerce_thankyou

עוקב אחר רכישות שהושלמו עם פרטי הזמנה.

add_action( 'woocommerce_thankyou', array( $this, 'track_purchase' ), 10, 1 );

פרמטרים:
$order_id (int) – מזהה ההזמנה שהושלמה

pre_get_posts

מיירט שאילתות חיפוש מוצרים למעקב אחר התנהגות חיפוש.

add_action( 'pre_get_posts', array( $this, 'track_product_search' ), 10, 1 );

פרמטרים:
$query (WP_Query) – אובייקט השאילתה


3. Actions מותאמים שמסופקים

hooks של do_action() אלו מאפשרים למפתחים להרחיב פונקציונליות תוסף בנקודות ביצוע מפתח.

woo_ai_chatbot_rtl_detected

מופעל כאשר שפת RTL (מימין לשמאל) מזוהה במהלך אתחול התוסף.

do_action( 'woo_ai_chatbot_rtl_detected' );

מקרה שימוש: טעינת stylesheets ספציפיים ל-RTL או שינוי התנהגות UI.

add_action( 'woo_ai_chatbot_rtl_detected', function() {
    // טעינת stylesheet RTL
    wp_enqueue_style(
        'woo-ai-chatbot-rtl',
        plugin_dir_url( __FILE__ ) . 'assets/css/rtl.css',
        array( 'woo-ai-chatbot' ),
        '1.0.0'
    );

    // הוספת class RTL ל-body
    add_filter( 'body_class', function( $classes ) {
        $classes[] = 'woo-ai-chatbot-rtl';
        return $classes;
    });
});

מופעל לאחר ביצוע חיפוש מוצרים, שימושי לאנליטיקה ו-debugging.

do_action( 'woo_ai_product_search', $search_term, $search_method, count( $products ) );

פרמטרים:
$search_term (string) – שאילתת החיפוש
$search_method (string) – שיטת חיפוש שנעשה בה שימוש (semantic, keyword, hybrid)
$count (int) – מספר תוצאות שהוחזרו

דוגמה:

add_action( 'woo_ai_product_search', function( $term, $method, $count ) {
    // רישום לאנליטיקה חיצונית
    error_log( sprintf(
        'WooAI Search: "%s" via %s returned %d results',
        $term,
        $method,
        $count
    ));

    // מעקב באנליטיקה מותאמת
    if ( class_exists( 'My_Analytics' ) ) {
        My_Analytics::track( 'chatbot_search', [
            'query' => $term,
            'method' => $method,
            'results' => $count,
        ]);
    }
}, 10, 3 );

4. Filters מותאמים שמסופקים

hooks של apply_filters() אלו מאפשרים שינוי נתונים והתנהגות של התוסף.

woo_ai_chatbot_should_display

שולט בנראות widget בצד לקוח.

$should_display = apply_filters( 'woo_ai_chatbot_should_display', true );

פרמטרים:
$should_display (bool) – האם widget צריך להיות מרונדר

מחזיר: bool

דוגמה:

add_filter( 'woo_ai_chatbot_should_display', function( $display ) {
    // הסתרה בקטגוריות מוצרים ספציפיות
    if ( is_product() ) {
        global $product;
        if ( has_term( 'restricted', 'product_cat', $product->get_id() ) ) {
            return false;
        }
    }

    // הסתרה לתפקידי משתמש ספציפיים
    if ( current_user_can( 'administrator' ) ) {
        return false; // מנהלים משתמשים בתמיכה ישירה
    }

    return $display;
});

woo_ai_chatbot_format_response

משנה את התגובה המפורמטת לפני החזרה לצד לקוח.

$response = apply_filters( 'woo_ai_chatbot_format_response', $response, $ai_response, $intent );

פרמטרים:
$response (array) – תגובה מפורמטת עם text, type, data, quickReplies
$ai_response (array) – תגובת AI גולמית
$intent (string) – Intent שזוהה (product_search, cart_help וכו’)

מחזיר: array

דוגמה:

add_filter( 'woo_ai_chatbot_format_response', function( $response, $ai_response, $intent ) {
    // הוספת מיתוג מותאם לכל התגובות
    $response['data']['branding'] = [
        'logo' => get_site_icon_url(),
        'name' => get_bloginfo( 'name' ),
    ];

    // הוספת באנר מבצע לחיפושי מוצרים
    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

מתאים אישית הצעות תגובה מהירה בהתבסס על intent.

$quick_replies = apply_filters( 'woo_ai_chatbot_quick_replies', $quick_replies, $intent );

פרמטרים:
$quick_replies (array) – מערך של ['label' => string, 'value' => string]
$intent (string) – Intent שזוהה

מחזיר: array

דוגמה:

add_filter( 'woo_ai_chatbot_quick_replies', function( $replies, $intent ) {
    // הוספת תגובות מהירות מותאמות לחיפוש מוצרים
    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

משנה הגדרות נושאים זמינות עבור מזהה הנושאים.

$topics = apply_filters( 'woo_ai_chatbot_topics', $topics );

פרמטרים:
$topics (array) – מערך אסוציאטיבי של הגדרות נושאים

מחזיר: array

דוגמה:

add_filter( 'woo_ai_chatbot_topics', function( $topics ) {
    // הוספת נושא מותאם לפניות אחריות
    $topics['warranty'] = [
        'slug'        => 'warranty',
        'name'        => 'Warranty Support',
        'keywords'    => ['warranty', 'guarantee', 'repair', 'broken', 'defect'],
        'patterns'    => ['/warrantys+(claim|policy|period)/i'],
        'priority'    => 80,
        'handler'     => 'WarrantyHandler',
        'description' => 'Product warranty and repair inquiries',
    ];

    return $topics;
});

woo_ai_chatbot_detected_topics

משנה תוצאות זיהוי נושאים לפני שהן משמשות לניתוב.

$result = apply_filters( 'woo_ai_chatbot_detected_topics', $result, $message, $context );

פרמטרים:
$result (array) – תוצאת זיהוי עם primary, secondary, confidence, keywords_matched
$message (string) – הודעת משתמש מקורית
$context (array) – הקשר session

מחזיר: array

דוגמה:

add_filter( 'woo_ai_chatbot_detected_topics', function( $result, $message, $context ) {
    // דריסת נושא בהתבסס על פלח משתמש
    $user_id = get_current_user_id();
    if ( $user_id && get_user_meta( $user_id, 'vip_customer', true ) ) {
        // לקוחות VIP תמיד מקבלים נושא תמיכה בעדיפות
        if ( $result['confidence'] < 0.5 ) {
            $result['primary'] = 'vip_support';
            $result['confidence'] = 0.9;
        }
    }

    return $result;
}, 10, 3 );

מסנן סטטיסטיקות נושאים מגמתיים לתצוגת אנליטיקה.

$topic_stats = apply_filters( 'woo_ai_chatbot_trending_topics', $topic_stats, $days );

פרמטרים:
$topic_stats (array) – סטטיסטיקות שימוש בנושאים
$days (int) – מספר ימים שנותחו

מחזיר: array

woo_ai_chatbot_topic_handlers

רושם handlers מותאמים לניתוב נושאים.

$handlers = apply_filters( 'woo_ai_chatbot_topic_handlers', $handlers );

פרמטרים:
$handlers (array) – מיפויי class handler ['topic_slug' => 'HandlerClass']

מחזיר: array

דוגמה:

add_filter( 'woo_ai_chatbot_topic_handlers', function( $handlers ) {
    $handlers['warranty'] = 'MyPluginHandlersWarrantyHandler';
    $handlers['appointments'] = 'MyPluginHandlersAppointmentHandler';
    return $handlers;
});

woo_ai_chatbot_match_playbook

דורס או משנה לוגיקת התאמת playbook.

$playbook = apply_filters( 'woo_ai_chatbot_match_playbook', $best_match, $message, $context );

פרמטרים:
$best_match (array|null) – Playbook שהותאם או null
$message (string) – הודעת משתמש
$context (array) – הקשר session

מחזיר: array|null

דוגמה:

add_filter( 'woo_ai_chatbot_match_playbook', function( $playbook, $message, $context ) {
    // אילוץ playbook ספציפי ללקוחות חוזרים
    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 ) {
            // החזרת playbook תמיכת VIP ללקוחות נאמנים
            return [
                'slug' => 'vip_support',
                'name' => 'VIP Customer Support',
                'priority' => 100,
            ];
        }
    }
    return $playbook;
}, 10, 3 );

woo_ai_chatbot_playbook_response

משנה תגובות ביצוע playbook.

$response = apply_filters( 'woo_ai_chatbot_playbook_response', $response, $playbook, $context );

פרמטרים:
$response (array) – תגובת Playbook עם text, type, quickReplies
$playbook (array) – נתוני Playbook שבוצע
$context (array) – הקשר session

מחזיר: array

דוגמה:

add_filter( 'woo_ai_chatbot_playbook_response', function( $response, $playbook, $context ) {
    // הוספת נתוני מעקב playbook
    $response['data']['playbook_id'] = $playbook['slug'];
    $response['data']['step'] = $context['current_step'] ?? 0;

    // הוספת אפשרות הסלמה ל-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

מתאים אישית את תגובת מידע משלוח.

$message = apply_filters( 'woo_ai_chatbot_shipping_info', $message );

פרמטרים:
$message (string) – הודעת משלוח ברירת מחדל

מחזיר: string

דוגמה:

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

מתאים אישית את תגובת מדיניות החזרות.

$message = apply_filters( 'woo_ai_chatbot_return_policy', $message );

פרמטרים:
$message (string) – הודעת מדיניות החזרות ברירת מחדל

מחזיר: string

דוגמה:

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

משנה תוצאות חיפוש לפני ואחרי שהגברת מבצע מוחלת.

$results = apply_filters( 'waa_search_results_before_boost', $results, $query );
// ... הגברת מבצע מוחלת ...
$results = apply_filters( 'waa_search_results_after_boost', $results, $query );

פרמטרים:
$results (array) – תוצאות חיפוש עם product_id, similarity, metadata
$query (string) – שאילתת חיפוש

מחזיר: array

דוגמה:

// החרגת מוצרים שאזלו מהמלאי לפני הגברה
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_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% לפריטים במבצע
            $item['on_sale'] = true;
        }
    }
    return $results;
}, 10, 2 );

5. משימות Cron

התוסף מתזמן מספר משימות רקע דרך WordPress cron.

woo_ai_chatbot_daily_index

רץ יומית לאינדוקס כל המוצרים לחיפוש סמנטי.

// מתוזמן בהפעלת תוסף
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' ] );

תדירות: יומית

woo_ai_chatbot_index_product

מאנדקס מוצר בודד (מופעל לאחר שמירת מוצר).

wp_schedule_single_event( time() + 10, 'woo_ai_chatbot_index_product', [ $product_id ] );

פרמטרים:
$product_id (int) – מזהה מוצר לאינדוקס

השהיה: 10 שניות אחרי שמירת מוצר

woo_ai_chatbot_cleanup

מבצע משימות תחזוקה שבועיות (ניקוי sessions ישנים, רוטציית לוגים).

if ( ! wp_next_scheduled( 'woo_ai_chatbot_cleanup' ) ) {
    wp_schedule_event( time(), 'weekly', 'woo_ai_chatbot_cleanup' );
}

תדירות: שבועית

woo_ai_chatbot_batch_index

מאנדקס מוצרים באצוות עבור קטלוגים גדולים.

add_action( 'woo_ai_chatbot_batch_index', [ $plugin, 'run_batch_index' ], 10, 2 );

פרמטרים:
$offset (int) – offset התחלה
$limit (int) – גודל אצווה

waa_cleanup_playbook_sessions

מנקה sessions של playbook שפג תוקפם.

if ( ! wp_next_scheduled( 'waa_cleanup_playbook_sessions' ) ) {
    wp_schedule_event( time(), 'hourly', 'waa_cleanup_playbook_sessions' );
}

תדירות: שעתית

woo_ai_supabase_keepalive

מונע מ-Supabase free tier להיכנס להשהיה עקב חוסר פעילות.

if ( ! wp_next_scheduled( 'woo_ai_supabase_keepalive' ) ) {
    wp_schedule_event( time(), 'daily', 'woo_ai_supabase_keepalive' );
}

תדירות: יומית


6. דוגמאות הרחבה

הוספת כלי AI מותאם

יצירת כלי מותאם ש-AI יכול להפעיל במהלך שיחות:

/**
 * רישום כלי AI מותאם להזמנת פגישות
 */
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' => 'MyPluginToolsAppointmentTool::handle',
    ];

    return $tools;
});

/**
 * class handler של כלי
 */
namespace MyPluginTools;

class AppointmentTool {
    public static function handle( $params, $context ) {
        $date = sanitize_text_field( $params['date'] );
        $time = sanitize_text_field( $params['time'] );

        // בדיקת זמינות
        $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
                ),
            ];
        }

        // הזמנת הפגישה
        $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
            ),
        ];
    }
}

שינוי הקשר צ’אט

הזרקת נתונים מותאמים להקשר AI לתגובות משופרות:

/**
 * הוספת נתוני נאמנות לקוח להקשר צ'אט
 */
add_filter( 'woo_ai_chatbot_session_context', function( $context, $session_id ) {
    $user_id = get_current_user_id();

    if ( $user_id ) {
        // הוספת דרגת נאמנות
        $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,
        ];

        // הוספת הזמנות אחרונות
        $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 );

הוספת צעד Playbook מותאם

יצירת סוגי צעדים מותאמים לאוטומציית playbook:

/**
 * רישום סוג צעד playbook מותאם לשליחת 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'     => 'MyPluginPlaybookEmailStep::execute',
        'parameters'  => [
            'to'       => [ 'type' => 'string', 'required' => true ],
            'subject'  => [ 'type' => 'string', 'required' => true ],
            'template' => [ 'type' => 'string', 'required' => true ],
        ],
    ];

    return $types;
});

/**
 * Step handler
 */
namespace MyPluginPlaybook;

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 ],
        ];
    }
}

הוספת אירועי אנליטיקה מותאמים

מעקב אחר אירועים מותאמים במערכת האנליטיקה של הצ’אטבוט:

/**
 * מעקב אחר אירועים מותאמים מביצועי playbook
 */
add_action( 'woo_ai_chatbot_playbook_step_completed', function( $playbook_slug, $step_index, $result, $context ) {
    // מעקב באנליטיקה של WooAI
    do_action( 'woo_ai_chatbot_track_event', 'playbook_step', [
        'playbook'   => $playbook_slug,
        'step'       => $step_index,
        'success'    => $result['success'] ?? false,
        'session_id' => $context['session_id'],
    ]);

    // מעקב באנליטיקה חיצונית
    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 );

/**
 * עזר מעקב אירועים מותאם
 */
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' ]
    );
}

שיטות עבודה מומלצות

  1. ניהול Priority: השתמשו ב-hook priorities מתאימים כדי להבטיח שהקוד שלכם רץ בזמן הנכון
  2. ביצועים: הימנעו מפעולות יקרות ב-filters שנקראים לעתים קרובות כמו woo_ai_chatbot_format_response
  3. תאימות: תמיד בדקו אם התוסף פעיל לפני hook לתוך ה-filters שלו
  4. אימות נתונים: סננו ואמתו את כל הנתונים ב-filter callbacks
  5. תיעוד: תעדו hooks מותאמים בהרחבה שלכם עבור מפתחים אחרים
// תמיד בדקו זמינות תוסף
if ( ! class_exists( 'WooAIChatbotPlugin' ) ) {
    return;
}

// השתמשו בפונקציות עם namespace למניעת התנגשויות
add_filter( 'woo_ai_chatbot_topics', 'MyPluginTopicsadd_custom_topics' );

תאימות גרסאות

Hook מאז גרסה הערות
woo_ai_chatbot_should_display 0.1.0 Filter ליבה
woo_ai_chatbot_format_response 0.1.0 Filter ליבה
woo_ai_chatbot_topics 0.2.0 מערכת נושאים
woo_ai_chatbot_match_playbook 0.3.0 מערכת Playbook
waa_search_results_before_boost 0.4.0 הגברת מבצעים
woo_ai_supabase_keepalive 0.4.5 אינטגרציית Supabase

לתמיכה נוספת, עיינו בתיעוד ארכיטקטורת תוסף או צרו קשר עם צוות הפיתוח.