❄️ Winter Sale: 40% OFF AIWU
WINTER_SECRET
Valid until Mar 1st
PHP Helper Functions: Integrate AI in Your WordPress Theme or Plugin - AIWU – AI Plugin for WordPress
Table of Contents
< All Topics

PHP Helper Functions: Integrate AI in Your WordPress Theme or Plugin

After reading this guide, you’ll be able to use AI directly in your WordPress theme or plugin PHP code — generating content, searching your knowledge base, and running AI operations server-side using AIWU’s PHP helper functions.

In this article: Core Functions · Content Generation · Knowledge Base Search · Trigger Workflows · Common Issues

💡 For PHP developers. These functions are available only in WordPress themes and plugins — not in JavaScript or external scripts. For external access, use the REST API.

Before You Start

You’ll need:

  • AIWU plugin v4.9+ installed and active
  • An AI provider configured in AIWU
  • Basic PHP / WordPress development knowledge
⚠️ Always check plugin is active before using AIWU functions:
if (function_exists('aiwu_generate_text')) { ... }

Core Functions Reference

Function Description Returns
aiwu_generate_text() Generate text with a prompt string | WP_Error
aiwu_chat() Send a message to a chatbot array | WP_Error
aiwu_search_knowledge() Search the trained knowledge base array | WP_Error
aiwu_trigger_workflow() Run an AIWU workflow programmatically array | WP_Error
aiwu_get_chatbot() Get a chatbot object by ID object | null

Text Generation

aiwu_generate_text( $prompt, $args )

$result = aiwu_generate_text(
    'Write a 2-sentence product description for: ' . get_the_title(),
    [
        'max_tokens'   => 150,
        'temperature'  => 0.7,
        'provider'     => 'openai',    // optional: overrides plugin default
        'model'        => 'gpt-4o-mini' // optional
    ]
);

if ( is_wp_error( $result ) ) {
    error_log( 'AIWU error: ' . $result->get_error_message() );
} else {
    echo esc_html( $result );
}

Practical: Auto-generate excerpt on post save

add_action( 'save_post', function( $post_id, $post ) {
    // Skip autosaves and revisions
    if ( wp_is_post_autosave( $post_id ) || wp_is_post_revision( $post_id ) ) return;
    // Only process published posts with no excerpt
    if ( $post->post_status !== 'publish' || ! empty( $post->post_excerpt ) ) return;
    if ( ! function_exists( 'aiwu_generate_text' ) ) return;

    $excerpt = aiwu_generate_text(
        'Write a 2-sentence excerpt for this article: ' . wp_strip_all_tags( $post->post_content ),
        [ 'max_tokens' => 100 ]
    );

    if ( ! is_wp_error( $excerpt ) ) {
        wp_update_post( [
            'ID'           => $post_id,
            'post_excerpt' => sanitize_text_field( $excerpt )
        ] );
    }
}, 10, 2 );

Chat with a Chatbot

aiwu_chat( $chatbot_id, $message, $session_id, $args )

$response = aiwu_chat(
    1,                          // chatbot ID
    'What is your return policy?',
    'session-' . get_current_user_id(),
    [
        'context' => 'User is on the checkout page',
    ]
);

if ( ! is_wp_error( $response ) ) {
    echo esc_html( $response['message'] );
    // $response['tokens_used'] — cost tracking
    // $response['model']       — which model responded
}

aiwu_search_knowledge( $query, $args )

$results = aiwu_search_knowledge(
    'shipping policy international orders',
    [
        'limit'      => 5,
        'min_score'  => 0.7,   // relevance threshold (0-1)
        'dataset_id' => null    // null = search all trained data
    ]
);

if ( ! is_wp_error( $results ) && ! empty( $results ) ) {
    foreach ( $results as $item ) {
        echo esc_html( $item['content'] );     // matched content
        echo ' (score: ' . $item['score'] . ')'; // relevance score
    }
}

Practical: Enrich chatbot with context before responding

// Search knowledge base for relevant info, then include in prompt
function my_aiwu_enhanced_response( $user_question ) {
    $knowledge = aiwu_search_knowledge( $user_question, [ 'limit' => 3 ] );

    $context = '';
    if ( ! is_wp_error( $knowledge ) ) {
        $context = "Relevant information:n";
        foreach ( $knowledge as $item ) {
            $context .= '- ' . $item['content'] . "n";
        }
    }

    return aiwu_generate_text(
        $context . "nUser question: " . $user_question . "nAnswer:",
        [ 'max_tokens' => 200 ]
    );
}

Trigger Workflows

aiwu_trigger_workflow( $workflow_id, $data )

// Trigger a workflow when a custom event happens
$result = aiwu_trigger_workflow(
    5,  // workflow ID
    [
        'user_email' => $user->user_email,
        'user_name'  => $user->display_name,
        'event_type' => 'custom_signup'
    ]
);

if ( is_wp_error( $result ) ) {
    error_log( 'Workflow trigger failed: ' . $result->get_error_message() );
}

Common Issues

Problem: “Call to undefined function aiwu_generate_text()”
Fix: AIWU is not active or the function name is wrong. Always wrap calls in if (function_exists('aiwu_generate_text')). Check plugin is active in WordPress Admin → Plugins.

Problem: Function returns WP_Error with “no_provider” message.
Fix: No AI provider is configured. Go to AI Copilot → Settings → AI Provider and add an API key.

Problem: aiwu_generate_text times out on long content.
Fix: Increase the timeout: [ 'timeout' => 60 ] in the $args array. For very long operations, use wp_schedule_single_event to run them asynchronously.

Problem: Getting the same response every time.
Fix: Temperature may be set to 0. Set 'temperature' => 0.7 in args for more varied outputs.

Still stuck? Check the AIWU Developer API Reference.

What’s Next

Last verified: AIWU v.4.9.2 · Updated: 2026-02-25

Scroll to Top