### Build JavaScript Assets (Shell) Source: https://10up.github.io/classifai/advanced-docs/extending-classifai Commands to manage JavaScript dependencies and build assets for production or development. Use `npm install` to install packages, `npm run build` for a production build, and `npm run start` for development with watch mode. ```shell # Install dependencies npm install # Build for production npm run build # Or start development watch mode npm run start ``` -------------------------------- ### Install Dependencies and Build (Manual) Source: https://10up.github.io/classifai/get-started/installation After cloning the repository, run these commands to install project dependencies and build the plugin for manual installation. ```bash git clone https://github.com/10up/classifai.git && cd classifai composer install && npm install && npm run build ``` -------------------------------- ### Run Elasticsearch Locally with Docker Source: https://10up.github.io/classifai/feature-configuration/smart-404 Use this command to download, install, and start Elasticsearch v7.9.0 locally. Access it at http://localhost:9200. Ensure security is disabled for local testing. ```bash docker run -p 9200:9200 -d --name elasticsearch \ -e "discovery.type=single-node" \ -e "xpack.security.enabled=false" \ -e "xpack.security.http.ssl.enabled=false" \ -e "xpack.license.self_generated.type=basic" \ docker.elastic.co/elasticsearch/elasticsearch:7.9.0 ``` -------------------------------- ### Get and Render Smart 404 Results Source: https://10up.github.io/classifai/feature-configuration/smart-404 Retrieves recommended results and allows for custom display logic. Supports arguments for index, number of results, candidate count, rescoring, and scoring function. The example shows how to loop through results and display post thumbnails and titles. ```php $results = Classifai\get_smart_404_results( [ 'index' => 'post', 'num' => 10, 'num_candidates' => 8000, 'rescore' => false, 'score_function' => 'cosine', ] ); ob_start(); // Render the results. foreach ( $results as $result ) { ?>
ID ) ) : ?>
ID ) ); ?>
post_title ); ?>
``` -------------------------------- ### Azure Key Vault Integration Source: https://10up.github.io/classifai/advanced-docs/programmatic-credentials Fetch credentials from Azure Key Vault for Azure OpenAI Providers. Ensure the Azure SDK is installed and configured. This example merges fetched secrets with existing credentials, prioritizing fetched values. ```php add_filter( 'classifai_provider_credentials', function( $credentials, $provider_id, $feature_id ) { // Only override for Azure Providers if ( ! str_starts_with( $provider_id, 'azure_' ) ) { return $credentials; } // Initialize Azure Key Vault client (requires Azure SDK) $vault_client = new AzureKeyVaultSecretClient( 'https://your-vault.vault.azure.net', new AzureIdentityDefaultAzureCredential() ); // Fetch secrets from Key Vault $api_key = $vault_client->getSecret( "classifai-{$provider_id}-api-key" )->getValue(); $endpoint = $vault_client->getSecret( "classifai-{$provider_id}-endpoint" )->getValue(); return array_merge( $credentials, [ 'api_key' => $api_key, 'endpoint_url' => $endpoint, // Keep deployment from settings if not in vault 'deployment' => $credentials['deployment'] ?? '', ] ); }, 10, 3 ); ``` -------------------------------- ### Index Terms with VIP CLI Source: https://10up.github.io/classifai/feature-configuration/term-cleanup Command to index all content, including creating vector embeddings for each term, on a WordPress VIP hosted environment. The `--setup` flag may be needed to ensure the schema is created correctly. ```bash vip @example-app.develop -- wp vip-search index --setup ``` -------------------------------- ### Feature-Specific Credentials Source: https://10up.github.io/classifai/advanced-docs/programmatic-credentials Assign different API keys for distinct features. This example uses a premium API key for content generation features and a standard key for others, by checking the `feature_id`. ```php add_filter( 'classifai_provider_credentials', function( $credentials, $provider_id, $feature_id ) { // Use premium API key for content generation if ( 'feature_content_generation' === $feature_id ) { $credentials['api_key'] = get_option( 'classifai_premium_api_key' ); } // Use standard API key for other features return $credentials; }, 10, 3 ); ``` -------------------------------- ### Create AI Language Model Instance Source: https://10up.github.io/classifai/advanced-docs/chrome-built-in-ai Execute this command in the Chrome DevTools console to force Chrome to recognize and attempt to create an instance of the AI language model. This step is intended to fail initially but helps in the setup process. ```javascript await ai.languageModel.create(); ``` -------------------------------- ### Environment Variable Credentials Source: https://10up.github.io/classifai/advanced-docs/programmatic-credentials Use environment variables for API keys and endpoint URLs instead of database storage. This example dynamically constructs environment variable names based on the provider ID and checks for their definition. ```php add_filter( 'classifai_provider_credentials', function( $credentials, $provider_id, $feature_id ) { // Convert provider_id to environment variable format $env_key = strtoupper( str_replace( '-', '_', "CLASSIFAI_{$provider_id}_API_KEY" ) ); if ( defined( $env_key ) ) { $credentials['api_key'] = constant( $env_key ); } // Handle Azure Providers that need endpoint_url if ( str_starts_with( $provider_id, 'azure_' ) ) { $env_endpoint = strtoupper( str_replace( '-', '_', "CLASSIFAI_{$provider_id}_ENDPOINT" ) ); if ( defined( $env_endpoint ) ) { $credentials['endpoint_url'] = constant( $env_endpoint ); } } return $credentials; }, 10, 3 ); ``` -------------------------------- ### Register Custom REST API Endpoints Source: https://10up.github.io/classifai/advanced-docs/extending-classifai Register a new REST API route for your extension. This example defines a POST endpoint for processing requests, including parameter validation and permissions. ```php /** * Register REST API endpoints. */ public function register_endpoints() { register_rest_route( 'my-extension/v1', '/process(?:/(?P\d+))?', [ 'methods' => 'POST', 'callback' => [ $this, 'process_request' ], 'permission_callback' => fn() => current_user_can( 'edit_posts' ), 'args' => [ 'id' => [ 'required' => true, 'type' => 'integer', 'sanitize_callback' => 'absint', 'validate_callback' => 'is_numeric', ], ], ] ); } ``` -------------------------------- ### classifai_xai_api_request_get_options Source: https://10up.github.io/classifai/hooks/Filters/classifai_xai_api_request_get_options Filters the options for the XAI API get request. ```APIDOC ## Filter: classifai_xai_api_request_get_options ### Description Filter the options for the get request. ### Parameters #### Arguments * **$options** (`array`) - The options for the request. * **$url** (`string`) - The URL for the request. * **$this->feature** (`string`) - The feature name. ### Since * 3.3.0 ### Source Defined in `includes/Classifai/Providers/XAI/APIRequest.php` at line 102 ### Returns The options for the request. ``` -------------------------------- ### classifai_xai_api_response_get Filter Source: https://10up.github.io/classifai/hooks/Filters/classifai_xai_api_response_get Filters the response from xAI for a GET request. This filter allows developers to modify the API response before it is finalized. ```APIDOC ## classifai_xai_api_response_get ### Description Filter the response from xAI for a get request. ### Parameters #### Path Parameters * **$response** (array|WP_Error) - Required - The API response. * **$url** (string) - Required - Request URL. * **$options** (array) - Required - Request body options. * **$this->feature** (string) - Required - Feature name. ### Since * 3.3.0 ### Source Defined in `includes/Classifai/Providers/XAI/APIRequest.php` at line 119 ### Returns API response. ``` -------------------------------- ### classifai_openai_api_request_get_options Source: https://10up.github.io/classifai/hooks/Filters/classifai_openai_api_request_get_options Filters the options for the OpenAI API get request. This filter allows developers to modify the request options before the API call is made. ```APIDOC ## Filter: classifai_openai_api_request_get_options ### Description Filters the options for the get request. ### Parameters #### Path Parameters - **$options** (array) - Required - The options for the request. - **$url** (string) - Required - The URL for the request. - **$this->feature** (string) - Required - The feature name. ### Since * 2.4.0 ### Source Defined in `includes/Classifai/Providers/OpenAI/APIRequest.php` at line 102 ### Returns The options for the request. ``` -------------------------------- ### Project package.json for Classifai Extension Source: https://10up.github.io/classifai/advanced-docs/extending-classifai Defines project metadata, build scripts, and dependencies for a Classifai extension. Includes WordPress scripts and components for UI development. ```json { "name": "my-classifai-extension", "version": "1.0.0", "scripts": { "build": "wp-scripts build src/index.js src/settings.js --output-path=build", "start": "wp-scripts start src/index.js src/settings.js --output-path=build" }, "dependencies": { "@wordpress/api-fetch": "^6.0.0", "@wordpress/components": "^25.0.0", "@wordpress/data": "^9.0.0", "@wordpress/element": "^5.0.0", "@wordpress/i18n": "^4.0.0", "@wordpress/plugins": "^6.0.0" }, "devDependencies": { "@wordpress/scripts": "^26.0.0" } } ``` -------------------------------- ### classifai_azure_openai_resize_content_request_body Filter Source: https://10up.github.io/classifai/hooks/Filters/classifai_azure_openai_resize_content_request_body This filter allows you to modify the request body before it is sent to Azure OpenAI for content resizing. It is available starting from version 2.3.0. ```APIDOC ## Filter: classifai_azure_openai_resize_content_request_body ### Description Filter the resize request body before sending to Azure OpenAI. ### Parameters #### Path Parameters * **$body** (array) - Required - Request body that will be sent. * **$post_id** (int) - Required - ID of post. ### Since * 2.3.0 ### Source Defined in `includes/Classifai/Providers/Azure/OpenAI.php` at line 628 ### Returns Request body. ``` -------------------------------- ### Create a Custom Provider Class in Classifai Source: https://10up.github.io/classifai/advanced-docs/useful-snippets Extend the base Classifai Provider class to create a custom provider. Ensure all required methods are implemented and set the unique Provider ID. ```php namespace MyPluginOrTheme; use Classifai\Providers\Provider; class MyProvider extends Provider { /** * The Provider ID. * * Required and should be unique. */ const ID = 'my_provider'; /** * MyProvider constructor. * * @param \Classifai\Features\Feature $feature_instance The feature instance. */ public function __construct( $feature_instance = null ) { $this->feature_instance = $feature_instance; } /** * Returns the default settings for this provider. * * @return array */ public function get_default_provider_settings(): array { $common_settings = [ 'api_key' => '', 'authenticated' => false, ]; return $common_settings; } /** * Sanitize the settings for this provider. * * Can also be useful to verify the Provider API connection * works as expected here, returning an error if needed. * * @param array $new_settings The settings array. * @return array */ public function sanitize_settings( array $new_settings ): array { $settings = $this->feature_instance->get_settings(); // Ensure proper validation of credentials happens here. $new_settings[ static::ID ]['api_key'] = sanitize_text_field( $new_settings[ static::ID ]['api_key'] ?? $settings[ static::ID ]['api_key'] ); $new_settings[ static::ID ]['authenticated'] = true; return $new_settings; } /** * Common entry point for all REST endpoints for this provider. * * All Features will end up calling the rest_endpoint_callback method for their assigned Provider. * This method should validate the route that is being called and then call the appropriate method * for that route. This method typically will validate we have all the required data and if so, * make a request to the appropriate API endpoint. * * @param int $post_id The Post ID we're processing. * @param string $route_to_call The route we are processing. * @param array $args Optional arguments to pass to the route. * @return string|WP_Error */ public function rest_endpoint_callback( $post_id = 0, string $route_to_call = '', array $args = [] ) { if ( ! $post_id || ! get_post( $post_id ) ) { return new WP_Error( 'post_id_required', esc_html__( 'A valid post ID is required to generate an excerpt.', 'text-domain' ) ); } $route_to_call = strtolower( $route_to_call ); $return = ''; // Handle all of our routes. switch ( $route_to_call ) { case 'test': // Ensure this method exists. $return = $this->generate( $post_id, $args ); break; } return $return; } /** * Returns the debug information for the provider settings. * * This is used to display various settings in the Site Health screen. * Not required but useful for debugging. * * @return array */ public function get_debug_information(): array { $settings = $this->feature_instance->get_settings(); $debug_info = []; return $debug_info; } } ``` -------------------------------- ### Implement Provider-Specific API Calls Source: https://10up.github.io/classifai/advanced-docs/extending-classifai Create a switch statement to handle API calls for different providers. Each provider should have its own dedicated method for specific implementation details. ```php private function call_provider_api( string $provider_id, array $settings, string $prompt, string $content ) { switch ( $provider_id ) { case ChatGPT::ID: return $this->call_chatgpt( $settings, $prompt, $content ); case GeminiAPI::ID: return $this->call_gemini( $settings, $prompt, $content ); default: return new \WP_Error( 'unsupported_provider', __( 'Unsupported provider.', 'my-extension' ) ); } } private function call_chatgpt( array $settings, string $prompt, string $content ) { // ChatGPT-specific implementation } private function call_gemini( array $settings, string $prompt, string $content ) { // Gemini-specific implementation } ``` -------------------------------- ### classifai_googleai_api_response_get Filter Source: https://10up.github.io/classifai/hooks/Filters/classifai_googleai_api_response_get This filter allows you to modify the response received from the Google AI API for a GET request. It is defined in `includes/Classifai/Providers/GoogleAI/APIRequest.php` and was introduced in version 3.0.0. ```APIDOC ## Filter: classifai_googleai_api_response_get ### Description Filter the response from Google AI for a get request. ### Parameters - **$response** (`array`|`WP_Error`) - API response. - **$url** (`string`) - Request URL. - **$options** (`array`) - Request body options. - **$this->feature** (`string`) - Feature name. ### Since * 3.0.0 ### Returns API response. ``` -------------------------------- ### classifai_ollama_key_takeaways_auto_run Source: https://10up.github.io/classifai/hooks/Filters/classifai_ollama_key_takeaways_auto_run Decide if we should automatically run the key takeaways generation. By default, we will always run the generation. If you only want to run when triggered manually, you can filter the return value to false. ```APIDOC ## Filter: classifai_ollama_key_takeaways_auto_run ### Description Decide if we should automatically run the key takeaways generation. By default, we will always run the generation. If you only want to run when triggered manually, you can filter the return value to false. ### Parameters #### Query Parameters - **$run** (bool) - Whether to run the key takeaways generation. - **$post_id** (int) - ID of post we are summarizing. ### Since * 3.5.0 ### Returns Whether to run the key takeaways generation. ``` -------------------------------- ### classifai_googleai_api_request_get_options Source: https://10up.github.io/classifai/hooks/Filters/classifai_googleai_api_request_get_options Filters the options for the Google AI API GET request. This filter allows developers to modify the request options before the API call is made. ```APIDOC ## Filter: classifai_googleai_api_request_get_options ### Description Filter the options for the get request. ### Parameters #### Path Parameters - **$options** (array) - Required - The options for the request. - **$url** (string) - Required - The URL for the request. - **$this->feature** (string) - Required - The feature name. ### Since * 3.0.0 ### Source Defined in `includes/Classifai/Providers/GoogleAI/APIRequest.php` at line 102 ### Returns The options for the request. ``` -------------------------------- ### classifai_xai_api_request_get_url Filter Source: https://10up.github.io/classifai/hooks/Filters/classifai_xai_api_request_get_url This filter allows you to modify the URL before a GET request is made in the Classifai XAI API. It accepts the URL, options, and the feature name as parameters. ```APIDOC ## Filter: classifai_xai_api_request_get_url ### Description Filter the URL for the get request. ### Parameters - **$url** (`string`) - Required - The URL for the request. - **$options** (`array`) - Required - The options for the request. - **$this->feature** (`string`) - Required - The feature name. ### Since * 3.3.0 ### Returns The URL for the request. ``` -------------------------------- ### classifai_feature_image_generation_rest_route_generate-image_args Source: https://10up.github.io/classifai/hooks/Filters/classifai_.staticID._rest_route_.route._args This filter allows you to modify the arguments for a specific REST route. The example filter name 'classifai_feature_image_generation_rest_route_generate-image_args' demonstrates how the filter name is constructed dynamically based on the route. ```APIDOC ## Filter: classifai_ . static::ID . _rest_route_ . $route . _args ### Description Filter the arguments for the REST route. This allows for adding or modifying the arguments for the route. The filter name is dynamic and based on the route. Example: classifai_feature_image_generation_rest_route_generate-image_args ### Parameters - **$args** (`array`) - Array of arguments for the REST route. ### Since * 3.0.0 ### Source Defined in `includes/Classifai/Features/ImageGeneration.php` at line 89 ### Returns Modified array of arguments. ``` -------------------------------- ### Create Custom Feature Class Source: https://10up.github.io/classifai/advanced-docs/extending-classifai Extend the `Feature` abstract class to create a custom feature. Ensure the `ID` constant is unique and follows the `feature_*` pattern. The `feature_setup()` method only runs when the feature is enabled. ```php label = __( 'My Custom Feature', 'my-extension' ); // Get all available Providers from the Service. $this->provider_instances = $this->get_provider_instances( LanguageProcessing::get_service_providers() ); // Define which Providers this Feature supports. $this->supported_providers = [ ChatGPT::ID => __( 'OpenAI ChatGPT', 'my-extension' ), // Add more Providers as needed ]; } /** * Set up hooks that run when the Feature is enabled. * * Only fires if the Feature is enabled in settings. */ public function feature_setup() { // Register REST API endpoints. add_action( 'rest_api_init', [ $this, 'register_endpoints' ] ); // Enqueue editor assets. add_action( 'enqueue_block_assets', [ $this, 'enqueue_editor_assets' ] ); // Enqueue admin assets (settings page). add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_admin_assets' ] ); } /** * Get default settings for the Feature. * * @return array Default settings. */ public function get_feature_default_settings(): array { return [ 'provider' => ChatGPT::ID, // Add your custom settings here ]; } /** * Sanitize settings before saving. * * @param array $new_settings Settings being saved. * @return array Sanitized settings. */ public function sanitize_default_feature_settings( array $new_settings ): array { // Sanitize your custom settings return $new_settings; } /** * Get description for the enable field. * * @return string Feature description. */ public function get_enable_description(): string { return esc_html__( 'Description of what your Feature does.', 'my-extension' ); } } ``` -------------------------------- ### classifai_openai_api_response_get Filter Source: https://10up.github.io/classifai/hooks/Filters/classifai_openai_api_response_get This filter allows you to modify the response received from an OpenAI API GET request before it is processed further. You can access and manipulate the response data, URL, options, and feature name. ```APIDOC ## classifai_openai_api_response_get ### Description Filters the response from OpenAI for a GET request. ### Parameters #### Path Parameters - **$response** (array|WP_Error) - Required - The API response. - **$url** (string) - Required - Request URL. - **$options** (array) - Required - Request body options. - **$this->feature** (string) - Required - Feature name. ### Since 2.4.0 ### Returns API response. ``` -------------------------------- ### Activate Term Index Feature (VIP CLI) Source: https://10up.github.io/classifai/feature-configuration/term-cleanup Use this command on a WordPress VIP hosted environment to activate the term index feature for Enterprise Search. ```bash vip @example-app.develop -- wp vip-search activate-feature terms ``` -------------------------------- ### classifai_openai_api_request_get_url Filter Source: https://10up.github.io/classifai/hooks/Filters/classifai_openai_api_request_get_url This filter allows you to modify the URL used for OpenAI API GET requests. It's particularly useful for adding custom parameters or altering the endpoint before the request is made. ```APIDOC ## Filter: classifai_openai_api_request_get_url ### Description Filter the URL for the get request. ### Parameters * **$url** (`string`) - Required - The URL for the request. * **$options** (`array`) - Required - The options for the request. * **$this->feature** (`string`) - Required - The feature name. ### Since * 2.4.0 ### Source Defined in `includes/Classifai/Providers/OpenAI/APIRequest.php` at line 88 ### Returns The URL for the request. ``` -------------------------------- ### classifai_pre_render_post_audio_controls Source: https://10up.github.io/classifai/hooks/Filters/classifai_pre_render_post_audio_controls Filters the audio player markup before display. Returning a non-false value will short-circuit building the block markup and instead will return your custom markup prepended to the post_content. Note that by using this filter, the custom CSS and JS files will no longer be enqueued, so you'll be responsible for either loading them yourself or loading custom ones. ```APIDOC ## classifai_pre_render_post_audio_controls ### Description Filters the audio player markup before display. Returning a non-false value from this filter will short-circuit building the block markup and instead will return your custom markup prepended to the post_content. Note that by using this filter, the custom CSS and JS files will no longer be enqueued, so you'll be responsible for either loading them yourself or loading custom ones. ### Parameters #### Filter Parameters - **$markup** (bool|string) - Required - Audio markup to use. Defaults to false. - **$content** (string) - Required - Content of the current post. - **$_post** (\WP_Post) - Required - The Post object. - **$audio_attachment_id** (int) - Required - The audio attachment ID. - **$audio_attachment_url** (string) - Required - The URL to the audio attachment file. ### Since * 2.2.3 ### Returns Custom audio block markup. Will be prepended to the post content. ``` -------------------------------- ### Call ChatGPT API using Classifai's APIRequest Source: https://10up.github.io/classifai/advanced-docs/extending-classifai This method handles the specific logic for calling the ChatGPT API. It retrieves the API key, constructs the request body, and uses `Classifai\Providers\OpenAI\APIRequest` for making the authenticated POST request. Ensure the API key is present in settings. ```php /** * Call ChatGPT API. * * @param array $settings Feature settings. * @param string $prompt System prompt. * @param string $content Content to process. * @return string|\[WP_Error Response or error. */ private function call_chatgpt( array $settings, string $prompt, string $content ) { $api_key = $settings[ ChatGPT::ID ]['api_key'] ?? ''; if ( empty( $api_key ) ) { return new \WP_Error( 'missing_api_key', __( 'API key is missing.', 'my-extension' ) ); } // Use ClassifAI's APIRequest class for authenticated requests. $request = new \Classifai\Providers\OpenAI\APIRequest( $api_key, $this->get_option_name() ); $body = [ 'model' => 'gpt-4o-mini', 'messages' => [ [ 'role' => 'system', 'content' => $prompt, ], [ 'role' => 'user', 'content' => $content, ], ], 'temperature' => 0.3, 'max_tokens' => 2000, ]; // Make the API request. $response = $request->post( 'https://api.openai.com/v1/chat/completions', [ 'body' => wp_json_encode( $body ), ] ); if ( is_wp_error( $response ) ) { return $response; } // Extract the response content. if ( ! empty( $response['choices'][0]['message']['content'] ) ) { return $response['choices'][0]['message']['content']; } return new \WP_Error( 'empty_response', __( 'Provider returned an empty response.', 'my-extension' ) ); } ``` -------------------------------- ### classifai_openai_speech_to_text_api_url Source: https://10up.github.io/classifai/hooks/Filters/classifai_openai_speech_to_text_api_url Filters the API URL used for OpenAI Speech to Text requests. This allows developers to modify the default URL if needed, for example, to point to a custom endpoint or a different version of the API. ```APIDOC ## Filter: classifai_openai_speech_to_text_api_url ### Description Filters the API URL. ### Parameters #### Query Parameters - **$url** (string) - The default API URL. ### Since - 3.4.0 ### Source Defined in `includes/Classifai/Providers/OpenAI/SpeechToText.php` at line 104 ### Returns The API URL. ``` -------------------------------- ### Add New AI Provider to Supported List Source: https://10up.github.io/classifai/advanced-docs/extending-classifai Update the constructor to include new AI providers in the list of supported options. This maps provider IDs to user-friendly names. ```php $this->supported_providers = [ ChatGPT::ID => __( 'OpenAI ChatGPT', 'my-extension' ), GeminiAPI::ID => __( 'Google AI (Gemini)', 'my-extension' ), // Add more as needed ]; ``` -------------------------------- ### classifai_googleai_gemini_api_.$args[resize_type]._content_prompt Source: https://10up.github.io/classifai/hooks/Filters/classifai_googleai_gemini_api_.argsresize_type._content_prompt Filters the resize prompt that will be sent to the Gemini API. This filter allows developers to modify the system prompt used for image resizing tasks. ```APIDOC ## Filter: classifai_googleai_gemini_api_ . $args[resize_type] . _content_prompt ### Description Filter the resize prompt we will send to Gemini API. ### Parameters - **$prompt** (string) - Required - Resize prompt we are sending to Gemini API. Gets added as a system prompt. - **$post_id** (int) - Required - ID of post. - **$args** (array) - Required - Arguments passed to endpoint. ### Since - 3.0.0 ### Source Defined in `includes/Classifai/Providers/GoogleAI/GeminiAPI.php` at line 472 ### Returns Prompt. ```