### Install Dependencies and Start WordPress Environment Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/tests/e2e/README.md Installs project dependencies, builds the plugin, installs PHP dependencies, and starts the WordPress environment using npm scripts. ```bash npm install npm run build && cd src && composer install && cd .. npm run wp-env:start ``` -------------------------------- ### Install Dependencies Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/AGENTS.md Installs Node.js and PHP dependencies. Husky hooks are also installed with Node dependencies. ```bash # Install dependencies npm install # Node deps + Husky hooks cd src && composer install # PHP deps (or: npm run bundle) ``` -------------------------------- ### Install Node.js Dependencies Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/CONTRIBUTING.md Installs the necessary node packages for the project. This should be run from the plugin directory. ```shell npm install ``` -------------------------------- ### Install WordPress Test Suite Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/tests/README.md Installs WordPress and the WP test suite, creating the test DB if necessary. Defaults can be overridden via environment variables. ```bash npm run test:setup:php ``` ```bash WP_PHPUNIT_DB_NAME=wp_phpunit_test \ WP_PHPUNIT_DB_USER=root \ WP_PHPUNIT_DB_PASS=root \ WP_PHPUNIT_DB_HOST=127.0.0.1 \ WP_PHPUNIT_WP_VERSION=latest \ npm run test:setup:php ``` -------------------------------- ### Start Local WordPress Environment Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/AGENTS.md Starts, stops, or resets a local WordPress environment using wp-env. ```bash # WordPress environment npm run wp-env:start # Start local WP instance npm run wp-env:stop npm run wp-env:clean # Reset all data ``` -------------------------------- ### Start WordPress Environment for Playwright Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/tests/README.md Starts the Docker-based WordPress environment required for Playwright tests. Includes options for cleaning and restarting. ```bash npm run wp-env:start ``` ```bash npm run wp-env:clean npm run wp-env:start ``` -------------------------------- ### Plugin Instance Usage Examples Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-plugin-class.md Demonstrates how to access various components and functionalities of the plugin through the globally accessed plugin instance. ```php // Access database $db = code_snippets()->db; $table = $db->get_table_name(false); // Access admin $admin = code_snippets()->admin; // Access evaluators $evaluator = code_snippets()->evaluate_functions; // Access cloud API $cloud = code_snippets()->cloud_api; $snippets = $cloud->search_snippets('dashboard'); // Access licensing $licensing = code_snippets()->licensing; $is_pro = $licensing->is_licensed(); // Check capabilities if (code_snippets()->current_user_can()) { // User can manage snippets } ``` -------------------------------- ### Model Constructor Example Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-models.md Demonstrates creating a new Snippet model instance with initial data, including name and code. ```php $snippet = new Snippet([ 'name' => 'My Snippet', 'code' => 'echo "test";' ]); ``` -------------------------------- ### Shortcode Usage Example Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-integration.md Example of how to use the [code_snippet] shortcode within WordPress content or a shortcode handler to display a specific snippet. ```php // In post content or shortcode handler echo do_shortcode('[code_snippet id="5"]'); ``` -------------------------------- ### Accessing WordPress Options Example Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/README.md Demonstrates how to retrieve a general setting from the Code Snippets plugin's WordPress options. ```php $value = code_snippets()->settings->get_setting('general', 'activate_by_default'); ``` -------------------------------- ### PHP Snippet Execution Example Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/README.md Demonstrates how to execute a PHP snippet with a global scope. This is a basic example of a PHP snippet that can be managed and executed by the plugin. ```php 'Add Custom Dashboard Widget', 'description' => 'Adds a custom widget to WordPress dashboard', 'code' => ' 'php', 'downloads' => 1250 ]); echo $cloud_snippet->name; echo $cloud_snippet->downloads . " downloads"; ``` -------------------------------- ### Install Playwright Dependencies Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/tests/README.md Installs JavaScript dependencies for Playwright E2E tests. Also installs Playwright browsers separately. ```bash npm ci ``` ```bash npx playwright install ``` -------------------------------- ### Defining Environment Variables Example Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/README.md Shows how to configure the Code Snippets plugin using environment variables in wp-config.php. ```php define('CS_CLOUD_API_URL', 'https://codesnippets.cloud/api/v1/'); define('CS_USE_FLAT_FILES', false); define('CS_DISABLE_EXECUTION', false); ``` -------------------------------- ### PHPUnit Example Test Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/tests/README.md A basic example of a PHPUnit test case for the Code Snippets plugin. ```php assertTrue( true ); } } ``` -------------------------------- ### Troubleshoot Docker Not Running Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/tests/e2e/README.md Checks if Docker is installed and running, and verifies Docker version. ```bash docker --version && docker ps ``` -------------------------------- ### Model get_fields() Example Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-models.md Fetches all fields of a snippet and iterates through them, printing each field name and its value. ```php $snippet = get_snippet(1); $fields = $snippet->get_fields(); foreach ($fields as $name => $value) { echo "$name: $value"; } ``` -------------------------------- ### Import Selected Snippets Request Body Example Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-rest-controllers.md Example JSON structure for the request body of the import_selected_snippets method, detailing the snippets to import, duplicate action, and network setting. ```json { "snippets": [ { "name": "...", "code": "...", "scope": "..." } ], "duplicate_action": "ignore", "network": false } ``` -------------------------------- ### Fix PHPUnit Permissions Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/tests/README.md Makes the WordPress test suite installation script executable. ```bash chmod +x tests/install-wp-tests.sh ``` -------------------------------- ### REST API Response Example Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/README.md Example of a successful JSON response from the Code Snippets REST API. ```json { "id": 1, "name": "My Snippet", "code": "...", "scope": "global", "active": true, "modified": "2024-05-23 12:00:00", "...": "other fields" } ``` -------------------------------- ### React Developers Reference Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/INDEX.md React developers should start with the React Hooks documentation and types, then reference utilities as needed. ```APIDOC ## React Development ### Description Resources for developers building React applications integrated with the system. ### Documentation Begin with [React Hooks](api-reference-react-hooks.md) for UI interactions and [Types](types.md) for data structures. [Utilities](api-reference-utilities.md) are available for common tasks. ### Usage React developers should familiarize themselves with the provided React Hooks and data types. Utility functions can be referenced as needed for additional support. ``` -------------------------------- ### Getting the Plugin Instance Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-plugin-class.md Provides instructions on how to access the singleton instance of the Plugin class using the global `code_snippets()` function. ```APIDOC ## Getting the Plugin Instance ### Singleton Pattern Access the single plugin instance globally: ```php $plugin = code_snippets(); ``` The `code_snippets()` function returns the singleton instance, creating it if necessary. ### Returns: * `Plugin` instance. ### Usage Examples: ```php // Access database $db = code_snippets()->db; $table = $db->get_table_name(false); // Access admin $admin = code_snippets()->admin; // Access evaluators $evaluator = code_snippets()->evaluate_functions; // Access cloud API $cloud = code_snippets()->cloud_api; $snippets = $cloud->search_snippets('dashboard'); // Access licensing $licensing = code_snippets()->licensing; $is_pro = $licensing->is_licensed(); // Check capabilities if (code_snippets()->current_user_can()) { // User can manage snippets } ``` ``` -------------------------------- ### Snippet Model Example Usage Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-models.md Demonstrates practical usage of the Snippet model, including creation, property access, modification, and checking features. ```APIDOC ## Snippet Model Example Usage ### Description Demonstrates practical usage of the Snippet model, including creation, property access, modification, and checking features. ### Example ```php use Code_Snippets\Model\Snippet; // Create from array $snippet = new Snippet([ 'name' => 'Hello World', 'code' => 'echo "Hello";', 'scope' => 'global', 'tags' => ['greet', 'example'] ]); // Access fields echo $snippet->name; // Hello World echo $snippet->code; // echo "Hello"; echo $snippet->scope_name; // Everywhere // Modify fields $snippet->priority = 20; $snippet->active = true; // Get all modified fields (for save operation) $to_save = $snippet->get_modified_fields(); // Check type if ($snippet->is_pro) { echo "This is a pro-only feature"; } ``` ``` -------------------------------- ### Snippet Model Example Usage Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-models.md Demonstrates creating a Snippet model instance, accessing its properties (including read-only ones), modifying fields, and checking its 'is_pro' status. ```php use Code_Snippets\Model\Snippet; // Create from array $snippet = new Snippet([ 'name' => 'Hello World', 'code' => 'echo "Hello";', 'scope' => 'global', 'tags' => ['greet', 'example'] ]); // Access fields echo $snippet->name; // Hello World echo $snippet->code; // echo "Hello"; echo $snippet->scope_name; // Everywhere // Modify fields $snippet->priority = 20; $snippet->active = true; // Get all modified fields (for save operation) $to_save = $snippet->get_modified_fields(); // Check type if ($snippet->is_pro) { echo "This is a pro-only feature"; } ``` -------------------------------- ### POST /code-snippets/v1/import/plugins Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/endpoints.md Import snippets from installed plugins. Specify the plugin identifier and optionally import to the network table for multisite. ```APIDOC ## POST /code-snippets/v1/import/plugins ### Description Import snippets from installed plugins. Specify the plugin identifier and optionally import to the network table for multisite. ### Method POST ### Endpoint /wp-json/code-snippets/v1/import/plugins ### Parameters #### Request Body - **plugin** (string) - Required - Plugin identifier (e.g., 'header-footer-code-manager/plugin.php'). - **network** (boolean) - Optional - Import to network table (multisite). ### Response #### Success Response (200 OK) - **imported** (array) - List of imported snippet IDs. - **errors** (array) - List of errors encountered during import. ### Request Example ```json { "plugin": "my-custom-plugin/my-plugin.php", "network": true } ``` ### Response Example ```json { "imported": [1, 2], "errors": [] } ``` ``` -------------------------------- ### Import Snippets from Installed Plugins Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/endpoints.md This endpoint allows importing snippets directly from an installed WordPress plugin. Provide the plugin's identifier and optionally specify network import. ```json { "imported": [1, 2], "errors": [] } ``` -------------------------------- ### Get Supported Languages for Highlighting Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-integration.md Retrieves an array of language codes supported by the code highlighter. ```php public static function get_languages(): array ``` -------------------------------- ### Get Plugin Instance (PHP) Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-utilities.md Retrieves the singleton instance of the main Plugin class. Use this to access plugin properties like database or settings. ```php function code_snippets(): Plugin ``` ```php $plugin = code_snippets(); $db = $plugin->db; $settings = $plugin->settings; ``` -------------------------------- ### REST API Reference Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/INDEX.md Understand the REST API by starting with the endpoints documentation, and then referencing types for request and response formats. ```APIDOC ## REST API ### Description Provides access to the system's functionality via RESTful endpoints. ### Documentation Refer to [endpoints.md](endpoints.md) for a detailed list of available endpoints and their usage. Reference [types.md](types.md) for request and response data structures. ### Usage Consumers should start with the `endpoints.md` documentation to understand the available operations and then consult `types.md` for the specific data formats required for requests and responses. ``` -------------------------------- ### Conditional Snippet Logic Example Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/README.md Shows how to define a condition that can control the execution of other snippets. This is a Pro feature for advanced logic. ```php search('dashboard', ['page' => 1, 'per_page' => 10]); echo "Found " . $cloud_snippets->total . " snippets"; foreach ($cloud_snippets->snippets as $snippet) { echo $snippet->name; } echo "Showing page " . $cloud_snippets->page . " of " . ceil($cloud_snippets->total / $cloud_snippets->per_page); ``` -------------------------------- ### code_snippets() Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-utilities.md Get the main plugin instance. This function provides access to the singleton instance of the main `Plugin` class, allowing retrieval of database and settings objects. ```APIDOC ## code_snippets() ### Description Get the main plugin instance. ### Returns Singleton instance of the main `Plugin` class. ### Usage ```php use function Code_Snippets\code_snippets; $plugin = code_snippets(); $db = $plugin->db; $settings = $plugin->settings; ``` ``` -------------------------------- ### PrismHighlighter Class Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-utilities.md Provides utilities for Prism syntax highlighting, including highlighting code, getting language definitions, and listing supported languages. ```APIDOC ## PrismHighlighter Class ### Description Utilities for Prism syntax highlighting. ### Methods #### highlight(code: string, language: string): string Highlights the given code string with the specified language. #### getLanguage(language: string): string | undefined Gets the Prism language definition for the given language string. #### getSupportedLanguages(): string[] Returns an array of all supported language strings. ``` -------------------------------- ### Setup Editor Preview Refresh Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-utilities.md Sets up the mechanism to refresh the preview iframe when editor settings are changed. This ensures the preview reflects the latest settings. ```typescript export function handleEditorPreviewUpdates(): void ``` -------------------------------- ### CSS Snippet for Frontend Example Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/README.md Demonstrates adding custom CSS to the website's frontend. This snippet type allows for site-wide styling modifications. ```css /* Snippet Name: Frontend Site Styles Snippet Description: Custom CSS for the website frontend. Snippet Type: css Snippet Scope: site-css */ body { background-color: #f0f0f0; } ``` -------------------------------- ### Model set_fields() Example Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-models.md Updates a snippet's fields with new values for 'name' and 'priority'. An 'unknown_field' is included to show it is ignored. ```php $snippet->set_fields([ 'name' => 'Updated', 'priority' => 20, 'unknown_field' => 'ignored' ]); ``` -------------------------------- ### Get Featured Cloud Snippets Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-integration.md Retrieve a collection of featured snippets from the cloud. Optional parameters can be passed via the options array. ```php public function get_featured_snippets(array $options = []): Cloud_Snippets ``` -------------------------------- ### Get All Site-Wide Snippets Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-snippet-operations.md Retrieves all snippets for the current site. Use an empty array for the IDs parameter and false for the network parameter. ```php use Code_Snippets\Model\Snippet; // Get all site-wide snippets $snippets = get_snippets([], false); foreach ($snippets as $snippet) { echo $snippet->name; // Snippet title } ``` -------------------------------- ### Plugin Entry Point Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-plugin-class.md The main plugin file (`code-snippets.php`) serves as the entry point, including plugin metadata and initiating the plugin's core class. ```php settings->get_setting('general', 'activate_by_default'); ?> ``` -------------------------------- ### Check User Permissions for Snippets Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-plugin-class.md Provides examples for checking user permissions to manage snippets, both site-wide and network-wide, using the plugin's helper functions and WordPress's built-in capabilities. ```php // Site-wide if (code_snippets()->current_user_can()) { // User can manage snippets } // Network-wide (multisite) if (code_snippets()->user_can_manage_network_snippets()) { // User can manage network snippets } // Current user if (current_user_can('manage_code_snippets')) { // Alternate method } ``` -------------------------------- ### JavaScript Snippet in Head Example Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/README.md Illustrates how to include a JavaScript snippet in the head section of the website. This is typically used for analytics, custom scripts, or third-party integrations. ```javascript // // Snippet Name: Frontend Head JS // Snippet Description: Adds a JavaScript snippet to the site's head. // Snippet Type: js // Snippet Scope: site-head-js // console.log( 'JavaScript snippet loaded in head.' ); ``` -------------------------------- ### Get Plugin Instance Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-plugin-class.md Accesses the singleton instance of the Plugin class globally using the `code_snippets()` function. This function creates the instance if it doesn't exist. ```php $plugin = code_snippets(); ``` -------------------------------- ### REST API Error Response Example Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/README.md Example of an error response from the Code Snippets REST API, including error code, message, and status. ```json { "code": "error_code", "message": "Human readable message", "data": { "status": 403 } } ``` -------------------------------- ### Example Usage of useSnippetsAPI Hook Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-react-hooks.md Illustrates how to use the `useSnippetsAPI` hook to perform common snippet management tasks like creating, updating, and toggling the active state of snippets. Ensure the component is wrapped by `WithSnippetsAPIContext`. ```typescript import { useSnippetsAPI } from '@hooks/useSnippetsAPI' function SnippetManager() { const snippetsAPI = useSnippetsAPI() const createSnippet = async () => { const newSnippet = await snippetsAPI.create({ name: 'My Snippet', code: 'echo "Hello";', scope: 'global', active: true }) console.log('Created:', newSnippet.id) } const updateName = async (id: number) => { await snippetsAPI.update({ id, network: false, name: 'New Name' }) } const toggleActive = async (snippet: Snippet) => { const updated = snippet.active ? await snippetsAPI.deactivate(snippet) : await snippetsAPI.activate(snippet) console.log('Now active:', updated.active) } return ( <> ) } ``` -------------------------------- ### initVersionSwitch() Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-utilities.md Initializes the version selector, allowing users to switch between released and development versions. ```APIDOC ## initVersionSwitch() ### Description Initialize version selector. ### Allows Switching between released and dev versions. ``` -------------------------------- ### Get Snippets API Instance Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-react-hooks.md Use `useSnippetsAPI` to get an instance of the SnippetsAPI for managing snippet CRUD operations. This hook requires the component to be wrapped by `WithSnippetsAPIContext` provider. ```typescript function useSnippetsAPI(): SnippetsAPI ``` -------------------------------- ### Accessing the Code Snippets Database Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-plugin-class.md Shows how to access the plugin's database object to get table names and perform custom queries using global $wpdb. Ensure proper table name retrieval and prepared statements for security. ```php $db = code_snippets()->db; // Get appropriate table name $table = $db->get_table_name($is_network); // Query global $wpdb; $snippets = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$table} WHERE id = %d", $snippet_id ) ); ``` -------------------------------- ### HTML Snippet Insertion Example Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/README.md Shows how to insert HTML content into the website's body. This snippet type is useful for adding custom HTML elements or scripts to specific locations. ```html
Hello from the body!
``` -------------------------------- ### Hooking into Plugin Initialization Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-plugin-class.md Demonstrates how to hook into the plugin's initialization process using the `code_snippets_init` action hook to access plugin functionality. ```php // After plugin init add_action('code_snippets_init', function() { $plugin = code_snippets(); // Custom logic }); ``` -------------------------------- ### Constructor Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-plugin-class.md Initializes the Plugin class by setting up core properties, registering controllers, and initializing integrations and hooks. ```APIDOC ## Constructor Initializes the Plugin class. ### Steps: 1. Register global cache groups 2. Set up class properties (db, admin, evaluators, etc.) 3. Register REST API controllers 4. Initialize integrations (shortcodes, admin bar, etc.) 5. Register activation/deactivation hooks ### Side Effects: * Loads WordPress cache group * Hooks into WordPress actions/filters * Initializes all subcomponents ``` -------------------------------- ### Build the Plugin Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/CONTRIBUTING.md Builds the plugin by processing SCSS and TypeScript files into browser-ready code. This command also copies vendor files. ```shell npm run build ``` -------------------------------- ### Welcome Page Configuration Data Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/configuration.md Configure data displayed on the Welcome page, such as hero information, changelog entries, and featured content. ```javascript window.CODE_SNIPPETS_WELCOME = { hero: { name: 'Hero Name', follow_url: 'https://...', image_url: 'https://...' }, changelog: [], // Recent version changes features: [], // Featured functionality partners: [] // Partner logos } ``` -------------------------------- ### Common wp-env Commands Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/tests/e2e/README.md Provides a list of common npm scripts for managing the WordPress environment and running tests. ```bash npm run wp-env:start # Start WordPress npm run wp-env:stop # Stop WordPress npm run wp-env:clean # Clean environment npm run test:playwright # Run tests npm run test:playwright:ui # Run with UI npm run test:playwright:debug # Debug mode ``` -------------------------------- ### Get Detailed License Information Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-integration.md Retrieves comprehensive information about the license status, including expiration and features. ```php public function get_license_status(): object ``` -------------------------------- ### Get MCE Plugin Settings Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-integration.md Retrieves the configuration settings for the MCE plugin, intended for JavaScript consumption. ```php public function get_plugin_settings(): array ``` -------------------------------- ### Accessing Plugin Instance Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/README.md Retrieve the main plugin instance to access its core components like the database, admin, and licensing modules. ```php $plugin = code_snippets(); $db = $plugin->db; $admin = $plugin->admin; $licensing = $plugin->licensing; ``` -------------------------------- ### Get i18n Locale (PHP) Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-utilities.md Retrieves the current internationalization locale using standard WordPress functions. ```php use function Code_Snippets\Utils\get_i18n_locale; // Get current locale $locale = get_i18n_locale(); ``` -------------------------------- ### user_can_manage_network_snippets() Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-plugin-class.md Checks if the current user has the capability to manage code snippets across the entire network in a multisite installation. ```APIDOC ## user_can_manage_network_snippets() Check if user can manage network-wide snippets. ### Returns: * (bool) - true if user has `manage_network_code_snippets` capability. ### Context: * Multisite only. * Targeted at Network Administrators. ``` -------------------------------- ### Prepare Playwright Environment Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/tests/README.md Prepares the WordPress environment for E2E testing by cleaning stale artifacts and ensuring the plugin is active. ```bash npm run test:setup:playwright ``` -------------------------------- ### DB Constructor Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-models.md Initializes table names and registers them with WordPress. This method sets the `$this->table` and `$this->ms_table` properties and registers the tables with the global `$wpdb` object. ```APIDOC ## DB::__construct() ### Description Initializes table names and registers them with WordPress. ### Side Effects: - Sets `$this->table` property - Sets `$this->ms_table` property - Registers tables with `$wpdb` ``` -------------------------------- ### Promotion Notice Display and Render Methods Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-integration.md Defines the methods required for promotion classes to determine display conditions and render the notice content. ```php public function should_display(): bool ``` ```php public function render_notice() ``` -------------------------------- ### Safe Mode Activation URL Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/README.md Illustrates how to activate safe mode by appending a query variable to a site URL. ```text ?snippets-safe-mode=1 ``` -------------------------------- ### Troubleshoot WordPress Port Availability Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/tests/e2e/README.md Checks for processes using port 8888 and restarts the WordPress environment if it fails to start. ```bash lsof -i :8888 # Check port availability npm run wp-env:stop && npm run wp-env:start ``` -------------------------------- ### PHP Development Reference Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/INDEX.md For PHP developers, begin with an overview of the Plugin Class, then reference specific classes and functions as needed. ```APIDOC ## PHP Development ### Description Documentation for PHP developers working with the plugin. ### Documentation Start with the [Plugin Class](api-reference-plugin-class.md) for a general overview. For specific operations, refer to [Snippet Operations](api-reference-snippet-operations.md). Model classes are documented in [Model Classes](api-reference-models.md). ### Usage PHP developers should consult the `api-reference-plugin-class.md` for the main entry points, and then dive into `api-reference-snippet-operations.md` and `api-reference-models.md` for detailed information on specific functionalities and data structures. ``` -------------------------------- ### Get Current Admin Screen Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-utilities.md Retrieves the slug of the current WordPress admin screen. Returns null if the screen cannot be determined. ```typescript export function getCurrentScreen(): string | null ``` -------------------------------- ### Enable Flat File Storage (PHP) Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/configuration.md Define a constant to enable storing snippets in flat files instead of the database. Set to true to use file-based storage. ```php define( 'CS_USE_FLAT_FILES', false ); ``` -------------------------------- ### GET /code-snippets/v1/snippets/schema Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/endpoints.md Retrieve the JSON Schema for the snippet object. This schema defines the structure, properties, and types for snippet data. ```APIDOC ## GET /code-snippets/v1/snippets/schema ### Description Retrieve the JSON Schema for the snippet object. This schema defines the structure, properties, and types for snippet data. ### Method GET ### Endpoint /wp-json/code-snippets/v1/snippets/schema ### Response #### Success Response (200 OK) - **JSON Schema definition** (object) - The schema defining snippet properties and types. ### Response Example ```json { "$schema": "http://json-schema.org/draft-07/schema#", "title": "Snippet", "type": "object", "properties": { "id": { "type": "integer", "description": "Unique identifier for the snippet." }, "name": { "type": "string", "description": "Name of the snippet." }, "description": { "type": "string", "description": "Description of the snippet." }, "scope": { "type": "string", "enum": ["global", "site", "network"], "description": "Scope of the snippet." }, "code": { "type": "string", "description": "The actual code content of the snippet." }, "tags": { "type": "array", "items": {"type": "string"}, "description": "Tags associated with the snippet." }, "active": { "type": "boolean", "description": "Whether the snippet is currently active." }, "modified": { "type": "string", "format": "date-time", "description": "Timestamp of the last modification." } }, "required": ["name", "code", "scope"] } ``` ``` -------------------------------- ### Enable and Configure Flat File Storage Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/configuration.md Enable flat file storage for snippets and specify a custom directory. Snippets will be stored as individual PHP files. ```php define( 'CS_USE_FLAT_FILES', true ); define( 'CS_FLAT_FILES_DIR', '/path/to/snippets/' ); ``` -------------------------------- ### GET /code-snippets/v1/recently-active Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/endpoints.md Retrieve a list of snippets that have been recently executed. This helps in identifying active or recently used code snippets. ```APIDOC ## GET /code-snippets/v1/recently-active ### Description Retrieve recently active snippets (snippets that have been executed). ### Method GET ### Endpoint /wp-json/code-snippets/v1/recently-active ### Parameters #### Query Parameters - **network** (boolean) - Optional - Scope: network-wide or site-wide. - **page** (integer) - Optional - Page number (default: 1). - **per_page** (integer) - Optional - Items per page (default: 10). ### Response #### Success Response (200 OK) ```json { "snippets": [ { "id": 1, "name": "Example Snippet", "last_active": 1716451200 } ] } ``` ### Permissions User must have `manage_code_snippets` capability. ``` -------------------------------- ### GET /code-snippets/v1/snippets/{id}/export Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/endpoints.md Export a specific snippet in JSON format. This allows for backup or migration of individual snippets. ```APIDOC ## GET /code-snippets/v1/snippets/{id}/export ### Description Export a snippet in JSON format. ### Method GET ### Endpoint /wp-json/code-snippets/v1/snippets/{id}/export ### Parameters #### Query Parameters - **network** (boolean) - Optional - Export from network-wide table (multisite). ### Response #### Success Response (200 OK) ```json { "snippets": [ { "name": "Example Snippet", "desc": "Description", "code": "echo 'Hello';", "tags": ["example"], "scope": "global" } ] } ``` ### Permissions User must have `manage_code_snippets` capability. ``` -------------------------------- ### GET /code-snippets/v1/snippets/{id} Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/endpoints.md Retrieves a single snippet by its unique ID. Can optionally fetch from network-wide storage in multisite environments. ```APIDOC ## GET /code-snippets/v1/snippets/{id} ### Description Retrieve a single snippet by its unique ID. Can optionally fetch from network-wide storage in multisite environments. ### Method GET ### Endpoint /wp-json/code-snippets/v1/snippets/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The snippet ID. #### Query Parameters - **network** (boolean) - Optional - Retrieve from network-wide table (multisite). ### Response #### Success Response (200 OK) - **id** (integer) - The snippet ID. - **name** (string) - The snippet name. - **desc** (string) - The snippet description. - **code** (string) - The snippet code. - **tags** (array) - Array of tags. - **scope** (string) - Snippet scope. - **priority** (integer) - Execution priority. - **active** (boolean) - Whether the snippet is active. - **locked** (boolean) - Whether the snippet is locked. - **trashed** (boolean) - Whether the snippet is trashed. - **network** (boolean) - Whether the snippet is network-wide. - **modified** (string) - The last modified timestamp. - **condition_id** (integer) - The ID of the linked condition snippet. ### Response Example ```json { "id": 1, "name": "Example Snippet", "desc": "A sample description", "code": "echo 'Hello';", "tags": ["example"], "scope": "global", "priority": 10, "active": true, "locked": false, "trashed": false, "network": false, "modified": "2024-05-23 12:00:00", "condition_id": 0 } ``` ### Permissions User must have `manage_code_snippets` capability. ``` -------------------------------- ### Model get_modified_fields() Example Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-models.md Creates a snippet with a name, then retrieves only the modified fields. The output shows only the 'name' field as it differs from the default. ```php $snippet = new Snippet(['name' => 'Test']); $modified = $snippet->get_modified_fields(); // Returns only: ['name' => 'Test'] // Excludes unchanged defaults like 'active' => false ``` -------------------------------- ### Build Project Assets Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/AGENTS.md Builds project assets using Webpack for development or distribution. Includes watch mode. ```bash # Build npm run build # Webpack build (JS + CSS → src/dist/) npm run watch # Webpack watch mode npm run bundle # Full distribution build → bundle/ ``` -------------------------------- ### Check for Software Updates Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-integration.md Connects to the license server to check for available software updates. Returns update information or null if the software is current. ```php public function check_for_updates(): ?object ``` -------------------------------- ### Get Cloud Service Base URL Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-integration.md Retrieves the base URL for the cloud service. Uses the CS_CLOUD_URL constant or a default value. ```php public static function get_cloud_url(): string ``` -------------------------------- ### Get All Snippet Tags Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-snippet-operations.md Retrieves a flat array of all unique tags used across all snippets. Useful for filtering or categorizing snippets. ```php function get_all_snippet_tags(): array {} ``` ```php $all_tags = get_all_snippet_tags(); foreach ($all_tags as $tag) { echo $tag; // 'example', 'shortcode', etc. } ``` -------------------------------- ### Get Last Validation Error Message Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-integration.md Retrieves the error message from the last validation attempt. Returns null if the code was valid. ```php public static function get_validation_error(): ?string ``` -------------------------------- ### Build URL with Query Parameters (JavaScript) Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-utilities.md Constructs a URL by appending query parameters to a base URL. Undefined or null parameters are omitted. ```typescript export function buildUrl( base: string | undefined, queryArgs: Record ): string ``` ```typescript buildUrl('/api/snippets', { network: false, page: 1, filter: undefined // Omitted }) // Returns: /api/snippets?network=0&page=1 ``` -------------------------------- ### Import Cloud Snippet Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-integration.md Import a specific snippet from the cloud to the local database using its cloud ID. Optionally import to the network table. ```php public function import_cloud_snippet( string $cloud_id, bool $network = false ): ?Snippet ``` -------------------------------- ### fetchQueryParam() Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-utilities.md Get query parameter from URL. This JavaScript utility function retrieves the value of a specified query parameter from the current URL. ```APIDOC ## fetchQueryParam() ### Description Get query parameter from URL. ### Parameters #### Path Parameters - **name** (string) - Required - The name of the query parameter to fetch. ### Returns The value of the query parameter, or undefined if not found. ### Example ```javascript const snippetId = fetchQueryParam('id') // Gets ?id=123 ``` ``` -------------------------------- ### GET /code-snippets/v1/snippets/{id}/export-code Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/endpoints.md Export only the code content of a snippet, without any metadata. Useful for direct use or integration into other systems. ```APIDOC ## GET /code-snippets/v1/snippets/{id}/export-code ### Description Export a snippet's code only (raw PHP/HTML/CSS/JS). ### Method GET ### Endpoint /wp-json/code-snippets/v1/snippets/{id}/export-code ### Parameters #### Query Parameters - **network** (boolean) - Optional - Export from network-wide table (multisite). ### Response #### Success Response (200 OK) Plain text code content. ### Permissions User must have `manage_code_snippets` capability. ``` -------------------------------- ### GET /code-snippets/v1/snippets Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/endpoints.md Retrieves a paginated collection of snippets. Supports filtering by network, status, order, and excluding specific snippet types. ```APIDOC ## GET /code-snippets/v1/snippets ### Description Retrieve a paginated collection of snippets. Supports filtering by network, status, order, and excluding specific snippet types. ### Method GET ### Endpoint /wp-json/code-snippets/v1/snippets ### Parameters #### Query Parameters - **network** (boolean) - Optional - Retrieve network-wide (true) or site-wide (false) snippets. In multisite, null defaults to current admin scope. - **page** (integer) - Optional - Which page of results to return. Defaults to 1. - **per_page** (integer) - Optional - Number of snippets per page. Defaults to 10. - **status** (string) - Optional - Filter by activation status: 'all', 'active', 'inactive'. Defaults to 'all'. - **orderby** (string) - Optional - Sort by 'id', 'name', or 'display_name'. - **order** (string) - Optional - Sort direction: 'asc' or 'desc'. Defaults to 'asc'. - **exclude_types** (array) - Optional - Array of snippet types to exclude (php, html, css, js, cond). Defaults to []. ### Response #### Success Response (200 OK) - **snippets** (array) - An array of snippet objects. - **page** (integer) - The current page number. - **per_page** (integer) - The number of snippets per page. - **total** (integer) - The total number of snippets. - **pages** (integer) - The total number of pages. ### Response Example ```json { "snippets": [ { "id": 1, "name": "Example Snippet", "desc": "A sample description", "code": "echo 'Hello';", "tags": ["example"], "scope": "global", "priority": 10, "active": true, "locked": false, "trashed": false, "network": false, "modified": "2024-05-23 12:00:00", "condition_id": 0, "shared_network": false } ], "page": 1, "per_page": 10, "total": 1, "pages": 1 } ``` ### Permissions User must have `manage_code_snippets` capability (or `manage_network_code_snippets` for network scope). ``` -------------------------------- ### Plugin Constructor Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-plugin-class.md The constructor initializes the Plugin class by setting up properties, registering hooks, and setting up integrations. ```php public function __construct() ``` -------------------------------- ### POST /code-snippets/v1/import/file-upload/import Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/endpoints.md Import parsed snippets into the database. Supports actions for handling duplicate entries and importing to the network table for multisite installations. ```APIDOC ## POST /code-snippets/v1/import/file-upload/import ### Description Import parsed snippets into the database. Supports actions for handling duplicate entries and importing to the network table for multisite installations. ### Method POST ### Endpoint /wp-json/code-snippets/v1/import/file-upload/import ### Parameters #### Request Body - **snippets** (array) - Required - Array of snippet objects to import. - **duplicate_action** (string) - Optional - Action on duplicates: 'ignore', 'replace', 'skip' (default: 'ignore'). - **network** (boolean) - Optional - Import to network table (multisite). ### Response #### Success Response (200 OK) - **imported** (array) - List of imported snippet IDs. - **duplicates** (array) - List of duplicate snippet identifiers. - **errors** (array) - List of errors encountered during import. ### Request Example ```json { "snippets": [ { "name": "My Snippet", "code": "", "description": "A simple hello world snippet." } ], "duplicate_action": "replace", "network": false } ``` ### Response Example ```json { "imported": [1, 2, 3], "duplicates": [], "errors": [] } ``` ``` -------------------------------- ### Model Constructor Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-models.md Initializes a model instance with optional data. Use this to set initial field values upon object creation. ```php public function __construct($initial_data = null) ``` -------------------------------- ### Check if Promotions Should Display Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-integration.md Determines if promotion notices should be displayed to the user. Returns true unless the 'hide_upgrade_menu' setting is enabled. ```php public function should_show_promotions(): bool ``` -------------------------------- ### Run Upgrades Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-integration.md The upgrade method checks for and applies necessary upgrades, including database schema changes, settings migration, and data transformation. ```php public function upgrade() ``` -------------------------------- ### Get Cloud API Endpoint URL Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-integration.md Retrieves the base URL for the cloud API endpoint. Uses CS_CLOUD_API_URL or derives it from the cloud URL. ```php public static function get_cloud_api_url(): string ``` -------------------------------- ### REST_Controller get_base_route() Method Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-rest-controllers.md Static method to get the full REST route path, including the namespace. Returns a string like 'code-snippets/v1/snippets'. ```php public static function get_base_route(): string ``` -------------------------------- ### downloadFile() Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-utilities.md Triggers a file download in the browser. It takes the file content, desired filename, and MIME type as arguments. ```APIDOC ## downloadFile() ### Description Trigger file download in browser. ### Parameters #### Path Parameters - **content** (string) - Required - File content. - **filename** (string) - Required - Downloaded filename. - **mimeType** (string) - Optional - MIME type. Defaults to 'text/plain'. ### Request Example ```typescript downloadFile('echo "test";', 'snippet.php', 'text/plain') ``` ``` -------------------------------- ### Apply Syntax Highlighting Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-integration.md Applies syntax highlighting to a given string of code. Defaults to PHP highlighting if no language is specified. ```php public static function highlight_code( string $code, string $language = 'php' ): string ``` -------------------------------- ### Get Single Snippet by ID Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-snippet-operations.md Retrieves a single snippet by its ID. If the snippet is not found, an empty Snippet object is returned with an ID of 0. ```php $snippet = get_snippet(42); if ($snippet->id) { echo "Found: " . $snippet->name; echo "Active: " . ($snippet->active ? 'Yes' : 'No'); echo "Code: " . $snippet->code; } else { echo "Snippet not found"; } ``` -------------------------------- ### Initialize Version Selector Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-utilities.md Initializes the version selector component. This allows users to switch between different released and development versions. ```typescript export function initVersionSwitch(): void ``` -------------------------------- ### GET /code-snippets/v1/cloud/snippets Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/endpoints.md Search and retrieve snippets from the Code Snippets Cloud library. This allows users to find and import snippets shared by the community. ```APIDOC ## GET /code-snippets/v1/cloud/snippets ### Description Search and retrieve cloud snippets from the Code Snippets Cloud library. ### Method GET ### Endpoint /wp-json/code-snippets/v1/cloud/snippets ### Parameters #### Query Parameters - **query** (string) - Required - Search term or CodeVault name. - **page** (integer) - Optional - Page number (default: 1). - **per_page** (integer) - Optional - Results per page (default varies, max 100). - **category** (string) - Optional - Filter by category (comma-separated). - **type** (string) - Optional - Filter by type (php, html, css, js; comma-separated). - **status** (string) - Optional - Filter by status ID (comma-separated). - **searchByCodevault** (boolean) - Optional - Treat query as CodeVault name. ### Response #### Success Response (200 OK) ```json { "snippets": [ { "id": "cloud-id-123", "name": "Cloud Snippet", "description": "Description from cloud", "code": "code here" } ], "page": 1, "per_page": 10, "total": 5 } ``` ### Permissions User must have `manage_code_snippets` capability. ``` -------------------------------- ### Register Promotion Notice Source: https://github.com/codesnippetspro/code-snippets/blob/core-beta/_autodocs/api-reference-integration.md Registers a specific promotion notice. Requires an instance of Promotion_Base. ```php public function register_promotion(Promotion_Base $promotion) ```