', ['selector' => '#message']);
hp_ds_patch_signals(['user_saved' => false, 'error' => $result['error']]);
}
```
--------------------------------
### Install HyperPress-Core
Source: https://github.com/estebanforge/hyperpress-core/blob/main/README.md
Use Composer to add the library to your project dependencies.
```bash
composer require estebanforge/hyperpress-core
```
--------------------------------
### Complete SSE Example
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/datastar-helpers.md
This example demonstrates how to implement Server-Sent Events (SSE) with rate limiting and progress updates using Datastar helpers. It includes rate limiting for uploads, initializing SSE, patching elements and signals to show progress, and finally completing the process with a client-side redirect.
```php
// hypermedia/process-upload.hp.php
5,
'time_window_seconds' => 300,
'identifier' => 'file_upload_' . get_current_user_id(),
'error_message' => __('Upload rate limit exceeded. You can upload 5 files every 5 minutes.', 'api-for-htmx'),
'error_selector' => '#upload-errors'
])) {
return; // Rate limited - error sent via SSE
}
// Initialize SSE
$sse = hp_ds_sse();
if (!$sse) {
hp_die('SSE not available');
}
// Show progress
hp_ds_patch_elements('
');
hp_ds_patch_signals(['progress' => 100, 'completed' => true]);
// Redirect after 2 seconds
hp_ds_execute_script('setTimeout(() => { window.location.href = "/dashboard"; }, 2000);');
?>
```
--------------------------------
### Example 'noswap/' Template File Structure
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/how-to-use.md
Illustrates the directory structure for 'noswap' hypermedia template partials.
```text
hypermedia/noswap/save-user.hp.php
hypermedia/noswap/delete-user.hp.php
```
--------------------------------
### Example Template File Structure
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/how-to-use.md
Illustrates the directory structure for hypermedia template partials within a theme.
```text
hypermedia/live-search.hp.php
hypermedia/related-posts.hp.php
hypermedia/private/author.hp.php
hypermedia/private/author-posts.hp.php
```
--------------------------------
### Install HyperPress via Composer
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/installation.md
Use this command to include HyperPress as a library in your own plugins or themes.
```bash
composer require estebanforge/hyperpress
```
--------------------------------
### Nonce and Request Validation Examples
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/security.md
Demonstrates how to use `hp_validate_request()` for basic nonce validation, validating specific actions, and validating custom data arrays. Also includes an example for real-time validation in a Datastar SSE endpoint.
```php
// Basic nonce validation (works for all hypermedia libraries)
if (!hp_validate_request()) {
hp_die('Security check failed');
}
// Validate specific action
if (!hp_validate_request($_REQUEST, 'delete_post')) {
hp_die('Invalid action');
}
// Validate custom data array
$custom_data = ['action' => 'save_settings', '_wpnonce' => $_POST['_wpnonce']];
if (!hp_validate_request($custom_data, 'save_settings')) {
hp_die('Validation failed');
}
// Datastar SSE endpoint with real-time validation
// hypermedia/validate-form.hp.php
$signals = hp_ds_read_signals();
$email = $signals['email'] ?? '';
$password = $signals['password'] ?? '';
// Validate email in real-time
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
hp_ds_patch_elements('
', ['selector' => '#password-error']);
hp_ds_patch_signals(['password_valid' => false]);
} else {
hp_ds_remove_elements('#password-error');
hp_ds_patch_signals(['password_valid' => true]);
}
```
--------------------------------
### hp_die Examples
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/how-to-use.md
Shows how to terminate execution with a hidden or visible error message.
```php
// Die with hidden error message
hp_die('Database connection failed');
// Die with visible error message
hp_die('Please fill in all required fields', true);
```
--------------------------------
### hp_ds_sse() usage
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/datastar-helpers.md
Example of getting or creating the ServerSentEventGenerator instance and checking its availability.
```php
$sse = hp_ds_sse();
if ($sse) {
// SSE is available, proceed with real-time updates
$sse->patchElements('
Connected
');
}
```
--------------------------------
### Define a Block with Fluent PHP API
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/hyperblocks.md
Example of a complete block implementation using the Fluent PHP API in a single file.
```php
setIcon('format-image')
->addFields([
Field::make('text', 'headline', 'Headline')
->setPlaceholder('Enter your headline')
->setRequired(true),
Field::make('textarea', 'subtitle', 'Subtitle')
->setPlaceholder('Enter subtitle text'),
Field::make('color', 'background_color', 'Background Color')
->setDefault('#ffffff'),
Field::make('color', 'text_color', 'Text Color')
->setDefault('#333333'),
Field::make('url', 'button_url', 'Button URL'),
Field::make('text', 'button_text', 'Button Text')
->setDefault('Learn More')
])
->setRenderTemplate('
');
// Register the block (auto-discovery will handle this)
return $heroBlock;
```
--------------------------------
### Minimal SSE Example - Frontend HTML
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/datastar-helpers.md
This HTML snippet shows how to consume the SSE endpoint on the frontend using Datastar attributes.
```html
Datastar SDK Demo
SSE events will be streamed from the backend to the frontend.
Hello, world!
```
--------------------------------
### hp_ds_location() redirect
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/datastar-helpers.md
Example of redirecting the browser to a new URL via SSE.
```php
// Redirect after processing
hp_ds_location('/dashboard');
// Redirect to external URL
hp_ds_location('https://example.com/success');
```
--------------------------------
### Passing Data via URL Parameters
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/how-to-use.md
Shows how to pass data to hypermedia templates using URL parameters for GET requests.
```text
/wp-html/v1/live-search?search=hello
/wp-html/v1/related-posts?category_id=5
```
--------------------------------
### Minimal SSE Example - Server-side
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/datastar-helpers.md
This PHP code snippet demonstrates the minimal server-side implementation for streaming updates via SSE using Datastar.
```php
// In your hypermedia template partial file, e.g., hypermedia/my-sse-endpoint.hp.php
// Apply rate limiting (SSE-specific; sends SSE error feedback when blocked)
if (hp_ds_is_rate_limited()) {
return; // Rate limited
}
// Initialize SSE (headers are sent automatically)
$sse = hp_ds_sse();
if (!$sse) {
hp_die('SSE not available');
}
// Read client signals
$signals = hp_ds_read_signals();
$delay = $signals['delay'] ?? 0;
$message = 'Hello, world!';
// Stream message character by character
for ($i = 0; $i < strlen($message); $i++) {
hp_ds_patch_elements('
' . substr($message, 0, $i + 1) . '
');
// Sleep for the provided delay in milliseconds
usleep($delay * 1000);
}
// Script will automatically exit and send the SSE stream
```
--------------------------------
### Configure Hyperpress via hyperpress/config/default_options
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/developer-configuration.md
Use this filter to override default plugin settings programmatically. This example demonstrates the full range of available configuration keys.
```php
add_filter('hyperpress/config/default_options', function($defaults) {
// General Settings
$defaults['active_library'] = 'htmx'; // 'htmx', 'alpinejs', or 'datastar'
$defaults['load_from_cdn'] = false; // `true` to use CDN, `false` for local files
// HTMX Core Settings
$defaults['load_hyperscript'] = true;
$defaults['load_alpinejs_with_htmx'] = false;
$defaults['set_htmx_hxboost'] = false;
$defaults['load_htmx_backend'] = false;
// Alpine Ajax Settings
$defaults['load_alpinejs_backend'] = false;
// Datastar Settings
$defaults['load_datastar_backend'] = false;
// HTMX Extensions - Enable by setting to `true`
$defaults['load_extension_ajax-header'] = false;
$defaults['load_extension_alpine-morph'] = false;
$defaults['load_extension_class-tools'] = false;
$defaults['load_extension_client-side-templates'] = false;
$defaults['load_extension_debug'] = false;
$defaults['load_extension_disable-element'] = false; // Note: key is 'disable-element'
$defaults['load_extension_event-header'] = false;
$defaults['load_extension_head-support'] = false;
$defaults['load_extension_include-vals'] = false;
$defaults['load_extension_json-enc'] = false;
$defaults['load_extension_loading-states'] = false;
$defaults['load_extension_method-override'] = false;
$defaults['load_extension_morphdom-swap'] = false;
$defaults['load_extension_multi-swap'] = false;
$defaults['load_extension_path-deps'] = false;
$defaults['load_extension_preload'] = false;
$defaults['load_extension_remove-me'] = false;
$defaults['load_extension_response-targets'] = false;
$defaults['load_extension_restored'] = false;
$defaults['load_extension_sse'] = false;
$defaults['load_extension_ws'] = false;
return $defaults;
});
```
--------------------------------
### hp_ds_patch_elements() basic usage
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/datastar-helpers.md
Basic example of patching HTML elements into the DOM via SSE.
```php
// Basic element patching
hp_ds_patch_elements('
Hello World
');
```
--------------------------------
### hp_ds_read_signals() usage
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/datastar-helpers.md
Example of reading client signals and using them for server-side processing.
```php
// Read client signals
$signals = hp_ds_read_signals();
$user_input = $signals['search_query'] ?? '';
$page_number = $signals['page'] ?? 1;
// Use signals for processing
if (!empty($user_input)) {
$results = search_posts($user_input, $page_number);
hp_ds_patch_elements($results_html, ['selector' => '#results']);
}
```
--------------------------------
### hp_ds_execute_script() simple usage
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/datastar-helpers.md
Example of executing a simple JavaScript code string on the client via SSE.
```php
// Simple script execution
hp_ds_execute_script('console.log("Server says hello!");');
```
--------------------------------
### Frontend HTML to consume the HTML endpoint
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/datastar-helpers.md
HTML structure to trigger a Datastar GET request and display the loaded content.
```html
Initial content
```
--------------------------------
### hp_ds_patch_signals() multiple signals update
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/datastar-helpers.md
Example of updating multiple Datastar signals on the client side.
```php
// Update multiple signals
hp_ds_patch_signals([
'loading' => false,
'message' => 'Data loaded successfully',
'timestamp' => time()
]);
```
--------------------------------
### hp_ds_remove_elements() with view transition
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/datastar-helpers.md
Example of removing elements from the DOM via SSE with a view transition effect.
```php
// Remove with view transition
hp_ds_remove_elements('.expired-items', ['useViewTransition' => true]);
```
--------------------------------
### Conditional Logic for Library vs. Plugin Mode
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/library-detection.md
Use `hp_is_library_mode()` to conditionally configure Hyperpress Core. When running as a Composer library, configuration is done via filters. When running as a WordPress plugin, full functionality is available, including admin interface setup.
```php
if (hp_is_library_mode()) {
// Running as composer library - no admin interface
// Configure via filters only
add_filter('hyperpress/default_options', function($defaults) {
$defaults['active_library'] = 'htmx';
return $defaults;
});
} else {
// Running as WordPress plugin - full functionality available
add_action('admin_menu', 'my_admin_menu');
}
```
--------------------------------
### hp_ds_patch_elements() advanced usage
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/datastar-helpers.md
Advanced example of patching HTML elements with options like selector, mode, and view transitions.
```php
// Advanced patching with options
hp_ds_patch_elements(
'
Task completed
',
[
'selector' => '.notifications',
'mode' => 'append',
'useViewTransition' => true
]
);
```
--------------------------------
### GET /hyperblocks/v1/block-fields
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/hyperblocks.md
Retrieves field definitions for a specified block name. This endpoint is used by the editor integration to dynamically load block settings.
```APIDOC
## GET /hyperblocks/v1/block-fields
### Description
Returns field definitions for the requested block name. This endpoint is crucial for the editor integration to render the block's Inspector Controls.
### Method
GET
### Endpoint
/hyperblocks/v1/block-fields
### Parameters
#### Query Parameters
- **name** (string) - Required - The name of the block for which to retrieve field definitions.
### Response
#### Success Response (200)
- **fields** (object) - An object containing the field definitions for the block.
- **permission** (string) - Indicates the permission required to access this endpoint, which is 'open' (`__return_true`).
### Response Example
```json
{
"fields": {
"headline": {"type": "text", "label": "Headline", "required": true, "placeholder": "Enter your headline"},
"subtitle": {"type": "textarea", "label": "Subtitle", "placeholder": "Enter subtitle text"},
"background_color": {"type": "color", "label": "Background Color", "default": "#ffffff"},
"text_color": {"type": "color", "label": "Text Color", "default": "#333333"},
"button_url": {"type": "url", "label": "Button URL"},
"button_text": {"type": "text", "label": "Button Text", "default": "Learn More"}
},
"permission": "__return_true"
}
```
```
--------------------------------
### hp_ds_execute_script() complex usage
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/datastar-helpers.md
Example of executing more complex JavaScript code on the client via SSE, including DOM manipulation and timers.
```php
// Complex client-side operations
hp_ds_execute_script('
document.querySelector("#progress").style.width = "100%";
setTimeout(() => {
location.reload();
}, 2000);
');
```
--------------------------------
### JSON Payload Example for Compact Input
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/options-compact-input.md
This JSON represents the data structure that the compact input feature will generate for the hidden input field upon form submission. It consolidates all option values into a single object.
```json
{ "hyperpress_options": { "site_tagline": "Hello", "enable_feature": "1", "favorite": "a" } }
```
--------------------------------
### hp_ds_patch_signals() conditional update
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/datastar-helpers.md
Example of updating a Datastar signal only if it does not already exist on the client.
```php
// Only patch if signal doesn't exist
hp_ds_patch_signals(['default_theme' => 'dark'], ['onlyIfMissing' => true]);
```
--------------------------------
### hp_ds_remove_elements() basic usage
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/datastar-helpers.md
Example of removing a specific element from the DOM via SSE.
```php
// Remove specific element
hp_ds_remove_elements('#temp-message');
```
--------------------------------
### Generating Endpoint URL with Helper
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/how-to-use.md
Demonstrates the recommended way to generate an endpoint URL for a hypermedia template using the `hp_get_endpoint_url` helper function.
```php
// Recommended: always use the helper
$url = hp_get_endpoint_url('live-search');
// Output: http://your-site.com/wp-html/v1/live-search
```
--------------------------------
### Conditional Loading Based on Environment
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/developer-configuration.md
Switch between different CDNs or local files based on the WordPress environment type.
```php
// Different sources for different environments
add_filter('hyperpress/assets/datastar_url', function($url, $load_from_cdn, $asset, $is_library_mode) {
if (wp_get_environment_type() === 'production') {
return 'https://your-production-cdn.com/datastar.min.js';
} elseif (wp_get_environment_type() === 'staging') {
return 'https://staging-cdn.com/datastar.js';
} else {
// Development - use local file
return $asset['local_url'];
}
}, 10, 4);
```
--------------------------------
### Handle Non-Standard Vendor Directories
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/developer-configuration.md
Implement custom logic to detect and resolve library paths in non-standard plugin directory structures.
```php
// Handle non-standard vendor directory structures
add_filter('hyperpress/assets/htmx_url', function($url, $load_from_cdn, $asset, $is_library_mode) {
if ($is_library_mode && empty($url)) {
// Custom detection for non-standard paths
$plugin_path = plugin_dir_path(__FILE__);
if (strpos($plugin_path, '/vendor-custom/') !== false) {
$custom_url = str_replace(WP_CONTENT_DIR, WP_CONTENT_URL, $plugin_path);
return $custom_url . 'assets/libs/htmx.min.js';
}
}
return $url;
}, 10, 4);
```
--------------------------------
### hp_ds_patch_signals() single signal update
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/datastar-helpers.md
Example of updating a single Datastar signal on the client side.
```php
// Update single signal
hp_ds_patch_signals(['user_count' => 42]);
```
--------------------------------
### Update Frontend Libraries
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/developer-configuration.md
Use these npm commands to synchronize local frontend library versions.
```bash
# Update all libraries
npm run update-all
# Update specific library
npm run update-htmx
npm run update-alpinejs
npm run update-hyperscript
npm run update-datastar
npm run update-all
```
--------------------------------
### Field CRUD Operations
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/helper-functions.md
Functions for getting, updating, and deleting fields (post/user/term meta, options).
```php
hp_get_field(string $name, $source = null, array $args = [])
hp_update_field(string $name, $value, $source = null, array $args = []): bool
hp_delete_field(string $name, $source = null, array $args = []): bool
```
--------------------------------
### Load Libraries from Custom CDN
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/developer-configuration.md
Use these filters to point library requests to a specific CDN URL.
```php
// Use your own CDN for all libraries
add_filter('hyperpress/assets/htmx_url', function($url, $load_from_cdn, $asset, $is_library_mode) {
return 'https://your-cdn.com/js/htmx@2.0.3.min.js';
}, 10, 4);
add_filter('hyperpress/assets/datastar_url', function($url, $load_from_cdn, $asset, $is_library_mode) {
return 'https://your-cdn.com/js/datastar@1.0.0.min.js';
}, 10, 4);
```
--------------------------------
### Run Test Suites
Source: https://github.com/estebanforge/hyperpress-core/blob/main/README.md
Execute various test suites using Pest v4 via Composer scripts.
```bash
composer run test
composer run test:unit
composer run test:integration
composer run test:feature
```
--------------------------------
### Force Specific Library Versions
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/developer-configuration.md
Ensure compatibility by forcing specific library versions and their corresponding URLs.
```php
// Force specific versions for compatibility
add_filter('hyperpress/assets/alpinejs_url', function($url, $load_from_cdn, $asset, $is_library_mode) {
return 'https://cdn.jsdelivr.net/npm/alpinejs@3.13.0/dist/cdn.min.js';
}, 10, 4);
add_filter('hyperpress/assets/alpinejs_version', function($version, $load_from_cdn, $asset, $is_library_mode) {
return '3.13.0';
}, 10, 4);
```
--------------------------------
### Register a block with the Fluent API
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/hyperblocks-examples.md
Uses the Fluent API to define a block with inline templates and field groups. Requires registration on the 'init' hook.
```php
use HyperPress\Blocks\Block;
use HyperPress\Blocks\FieldGroup;
use HyperPress\Blocks\Registry;
use HyperPress\Fields\HyperFields; // for field definitions
add_action('init', function () {
// Define a field group (reusable)
$group = new FieldGroup('cardFields');
$group->addField(
HyperFields::makeField('text', 'title', 'Title')->setDefault('Hello')
);
$group->addField(
HyperFields::makeField('textarea', 'body', 'Body')
);
// Register the group
Registry::getInstance()->registerFieldGroup($group);
// Create a block
$block = new Block('hyper/card');
$block->setTitle('Hyper Card')
->setIcon('id')
// Inline template (PHP allowed)
->setRenderTemplate('
{{ body }}
')
->addField( HyperFields::makeField('text', 'title', 'Title') )
->addField( HyperFields::makeField('textarea', 'body', 'Body') )
->addFieldGroup('cardFields');
// Register with the registry (auto-registers on init)
Registry::getInstance()->registerFluentBlock($block);
});
```
--------------------------------
### Backend Template - Search Execution
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/datastar-helpers.md
This PHP backend template executes the user search based on the provided query, simulates a delay, retrieves users from the database, and updates the UI with the results.
```php
20,
'time_window_seconds' => 60,
'identifier' => 'user_search_' . get_current_user_id(),
'error_message' => __('Search rate limit exceeded. Please wait before searching again.', 'api-for-htmx'),
'error_selector' => '#search-errors'
])) {
// Rate limit exceeded - error already sent to client via SSE
return;
}
// Get search parameters
$signals = hp_ds_read_signals();
$query = sanitize_text_field($signals['query'] ?? '');
// Set loading state
hp_ds_patch_signals(['loading' => true, 'results' => []]);
hp_ds_patch_elements('
', ['selector' => '#search-results']);
hp_ds_patch_signals(['loading' => false, 'results' => []]);
}
?>
```
--------------------------------
### Define a block using block.json
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/hyperblocks-examples.md
Standard WordPress block configuration and associated render template for auto-discovery.
```json
{
"name": "hyper/cta",
"title": "Hyper CTA",
"icon": "megaphone",
"category": "widgets",
"attributes": {
"text": { "type": "string", "default": "Click me" },
"url": { "type": "string", "default": "#" }
},
"supports": { "html": false }
}
```
```php
```
--------------------------------
### Generate Test Coverage Reports
Source: https://github.com/estebanforge/hyperpress-core/blob/main/README.md
Generate code coverage reports for the project using Composer scripts.
```bash
composer run test:coverage
composer run test:summary
composer run test:clover
```
--------------------------------
### Use RichText and InnerBlocks in templates
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/hyperblocks-examples.md
Demonstrates the use of component tags within templates for rendering attributes and nested block content.
```html
```
--------------------------------
### Retrieve Template Endpoint URLs
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/developer-configuration.md
Generate URLs for templates using namespaced paths or default theme paths.
```php
// Loads the template from: YOUR_PLUGIN_PATH/hypermedia/template-name.hp.php
echo hp_get_endpoint_url( 'my-plugin:template-name' );
// Loads the template from: YOUR_PLUGIN_PATH/hypermedia/parts/header.hp.php
echo hp_get_endpoint_url( 'my-plugin:parts/header' );
```
```php
// Loads: wp-content/themes/your-theme/hypermedia/live-search.hp.php
echo hp_get_endpoint_url( 'live-search' );
// Loads: wp-content/themes/your-theme/hypermedia/subfolder/my-listing.hp.php
echo hp_get_endpoint_url( 'subfolder/my-listing' );
```
--------------------------------
### POST /hyperblocks/v1/render-preview
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/hyperblocks.md
Renders a preview of a block with given attributes. This endpoint is used for live previews in the editor and handles both Fluent blocks and JSON blocks.
```APIDOC
## POST /hyperblocks/v1/render-preview
### Description
Renders a preview of a block with the provided attributes. This endpoint is used for live previews within the WordPress editor.
### Method
POST
### Endpoint
/hyperblocks/v1/render-preview
### Parameters
#### Request Body
- **blockName** (string) - Required - The name of the block to render.
- **attributes** (object) - Required - An object containing the attributes for the block.
### Request Example
```json
{
"blockName": "my-plugin/my-block",
"attributes": {
"headline": "Welcome to HyperBlocks",
"subtitle": "Build amazing WordPress blocks with PHP."
}
}
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the rendering was successful.
- **html** (string) - The rendered HTML of the block if successful.
- **error** (string) - An error message if rendering failed.
#### Response Example
```json
{
"success": true,
"html": "
Welcome to HyperBlocks
Build amazing WordPress blocks with PHP.
"
}
```
### Notes on Sanitization and Security
- Attributes are sanitized against HyperFields definitions before rendering.
- This endpoint requires `current_user_can('edit_posts')` permission. Avoid exposing it to unauthenticated users.
```
--------------------------------
### hp_ds_send_html() usage
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/datastar-helpers.md
Example of sending a plain text/html response without SSE framing, useful for Datastar's @get/@post actions or HTMX/Alpine AJAX.
```php
// Return HTML directly — Datastar will morph it by matching element IDs
```
--------------------------------
### Register a block with a file template
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/hyperblocks-examples.md
Registers a block using an external file for rendering. The template path is resolved relative to the plugin root.
```php
use HyperPress\Blocks\Block;
use HyperPress\Blocks\Registry;
use HyperPress\Fields\HyperFields;
add_action('init', function () {
$block = new Block('hyper/hero');
$block->setTitle('Hyper Hero')
->setIcon('slides')
// Use a file template; prefix is required
->setRenderTemplateFile('hyperblocks/hero/render')
->addField( HyperFields::makeField('text', 'title', 'Title')->setDefault('Welcome') )
->addField( HyperFields::makeField('text', 'subtitle', 'Subtitle') );
Registry::getInstance()->registerFluentBlock($block);
});
```
```php
```
--------------------------------
### Datastar (SSE / HTML) Integration
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/helper-functions.md
Helpers for integrating with Datastar for Server-Sent Events and HTML updates.
```php
hp_ds_sse(): ?ServerSentEventGenerator
hp_ds_read_signals(): array
hp_ds_patch_elements(string $html, array $options = []): void
hp_ds_remove_elements(string $selector, array $options = []): void
hp_ds_patch_signals(mixed $signals, array $options = []): void
hp_ds_execute_script(string $script, array $options = []): void
hp_ds_location(string $url): void
hp_ds_send_html(string $html): void
```
--------------------------------
### Frontend HTML for Rate Limiting Integration
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/datastar-helpers.md
HTML structure for a chat interface that dynamically updates based on rate limiting signals.
```html
Real-time Chat
Rate limit reached. Please wait before sending more messages.
Requests remaining:
```
--------------------------------
### Frontend HTML for User Search
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/datastar-helpers.md
This HTML structure sets up a live user search interface with real-time validation and dynamic result display using Datastar attributes.
```html
User Search
No users found
```
--------------------------------
### block.json Configuration for Hero Banner
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/hyperblocks.md
Defines the name, title, description, category, icon, attributes, and rendering method for a WordPress block. Ensure all attribute types and defaults are correctly specified.
```json
{
"name": "my-plugin/hero-banner",
"title": "Hero Banner",
"description": "A customizable hero banner block",
"category": "layout",
"icon": "format-image",
"attributes": {
"headline": {
"type": "string",
"default": "Welcome to Our Site"
},
"subtitle": {
"type": "string",
"default": "Amazing things happen here"
},
"backgroundColor": {
"type": "string",
"default": "#ffffff"
},
"textColor": {
"type": "string",
"default": "#333333"
},
"buttonUrl": {
"type": "string",
"default": "#"
},
"buttonText": {
"type": "string",
"default": "Learn More"
}
},
"supports": {
"align": ["wide", "full"],
"html": false
},
"render": "file:./render.php"
}
```
--------------------------------
### URL Generation Function: hp_get_endpoint_url()
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/how-to-use.md
Demonstrates various uses of the `hp_get_endpoint_url` helper function for generating endpoint URLs.
```php
// Basic usage
echo hp_get_endpoint_url('live-search');
// Output: http://your-site.com/wp-html/v1/live-search
// With subdirectories
echo hp_get_endpoint_url('admin/user-list');
// Output: http://your-site.com/wp-html/v1/admin/user-list
// With namespaced templates (plugin/theme specific)
echo hp_get_endpoint_url('my-plugin:dashboard/stats');
// Output: http://your-site.com/wp-html/v1/my-plugin:dashboard/stats
```
--------------------------------
### Full-screen layout CSS
Source: https://github.com/estebanforge/hyperpress-core/blob/main/assets/index.html
Applies full viewport dimensions to the document body and iframe elements.
```css
html, body { padding: 0; margin: 0; overflow: hidden; height: 100vh; width: 100vw; } iframe { height: 100vh; width: 100vw; }
```
--------------------------------
### Datastar-Specific Library Mode Configuration
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/library-detection.md
Configure Datastar for production use as a library by setting specific options via filters. This includes enabling local file loading and backend functionality. In plugin mode, users can configure these settings via the admin interface.
```php
// Datastar-specific library mode configuration
if (hp_is_library_mode()) {
// Configure Datastar for production use as library
add_filter('hyperpress/default_options', function($defaults) {
$defaults['active_library'] = 'datastar';
$defaults['load_from_cdn'] = false; // Use local files for reliability
$defaults['load_datastar_backend'] = true; // Enable in wp-admin
return $defaults;
});
// Register custom SSE endpoints for the plugin using this library
add_filter('hyperpress/register_template_path', function($paths) {
$paths['my-plugin'] = plugin_dir_path(__FILE__) . 'datastar-templates/';
return $paths;
});
} else {
// Plugin mode - users can configure via admin interface
// Add custom Datastar functionality only when running as main plugin
add_action('wp_enqueue_scripts', function() {
if (get_option('hyperpress_active_library') === 'datastar') {
wp_add_inline_script('datastar', 'console.log("Datastar ready for SSE!");');
}
});
}
```
--------------------------------
### Configure HyperPress Options Programmatically
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/developer-configuration.md
Use this filter to programmatically set default options for HyperPress when the admin interface is disabled. This allows for full configuration via code.
```php
add_filter('hyperpress/config/default_options', function($defaults) {
// Your configuration here. See above for examples.
return $defaults;
});
```
--------------------------------
### Echo Endpoint URL Function: hp_endpoint_url()
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/how-to-use.md
Shows how to use the `hp_endpoint_url` function to directly echo endpoint URLs, useful for template output with different hypermedia libraries.
```php
// HTMX usage
Loading...
// Datastar usage
Load Profile
// Alpine Ajax usage
')">
Refresh Stats
```
--------------------------------
### Backend Template - Real-time Validation
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/datastar-helpers.md
This PHP backend template handles real-time validation of the user search query, providing immediate feedback to the user and updating signals.
```php
0) {
hp_ds_patch_elements(
'
',
['selector' => '#search-validation']
);
}
?>
```
--------------------------------
### Register Plugin Template Path
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/developer-configuration.md
Register a custom namespace for template files using the hyperpress/render/register_template_path filter.
```php
add_filter( 'hyperpress/render/register_template_path', function( $paths ) {
// Ensure YOUR_PLUGIN_PATH is correctly defined, e.g., plugin_dir_path( __FILE__ )
// 'my-plugin' is the namespace.
$paths['my-plugin'] = YOUR_PLUGIN_PATH . 'hypermedia/';
return $paths;
});
```
--------------------------------
### render.php Template for Hero Banner
Source: https://github.com/estebanforge/hyperpress-core/blob/main/docs/hyperblocks.md
Renders the HTML for the hero banner block using attributes defined in block.json. It safely escapes output to prevent security vulnerabilities. Ensure all attribute fallbacks are sensible.
```php