Dynamic and Static WP Blocks

User
how to use both dynamic and static rendering wp blocks
Assistant
Using both dynamic and static rendering in WordPress blocks allows for a mix of client-side flexibility and server-side consistency. Here’s how to set up both types of blocks:

### 1. Static Rendering
Static blocks are primarily used when content does not need to change dynamically after being saved in the editor. Here’s how to set one up:

– **Register the Block**: Create the block in JavaScript (typically `block.js`).
– **Edit and Save Functions**: Use `edit` and `save` functions in JavaScript to handle rendering.
– `edit` function: Defines how the block will look in the editor.
– `save` function: Defines the HTML structure saved in the database and rendered on the front end.

Example:

wp.blocks.registerBlockType('my-plugin/static-block', {
    title: 'Static Block',
    icon: 'smiley',
    category: 'widgets',
    edit: () => {
        return <p>Hello, static block!</p>;
    },
    save: () => {
        return <p>Hello, static block!</p>;
    },
});

### 2. Dynamic Rendering
Dynamic blocks are rendered on the server side, allowing data or content to change each time the page loads. This is useful when you want real-time data, like recent posts or user-specific information.

– **Register the Block in PHP**: Define the block in PHP so that it can be rendered dynamically.
– **Render Callback**: Use a `render_callback` to handle what content gets displayed on the front end.

Example:

function register_dynamic_block() {
    register_block_type('my-plugin/dynamic-block', [
        'render_callback' => 'render_dynamic_block',
    ]);
}

function render_dynamic_block($attributes) {
    return '<p>Hello, dynamic block! The current time is ' . date('H:i:s') . '</p>';
}

add_action('init', 'register_dynamic_block');

### Using Both Together

For blocks that need to have both static and dynamic elements:

1. **JavaScript Part**: Use the `edit` function to control how the block appears in the editor.
2. **PHP Part**: Use `render_callback` in PHP to dynamically render parts of the content on the front end.

For example, you could set up a block that shows static content in the editor but fetches dynamic content when viewed on the site.

### Example Hybrid Block

// In PHP (register the block)
function register_hybrid_block() {
    register_block_type('my-plugin/hybrid-block', [
        'editor_script' => 'my-plugin-block-editor',
        'render_callback' => 'render_hybrid_block',
    ]);
}

function render_hybrid_block($attributes) {
    return '<p>Dynamic content: ' . get_the_date() . '</p><p>Static message: Hello!</p>';
}

add_action('init', 'register_hybrid_block');

In this setup, only part of the block output is dynamic, and you control the static portion via JavaScript, providing flexibility on both ends.

User
we are using block.json
Assistant
User is using `block.json` for defining WordPress blocks.
Assistant
Using `block.json` simplifies block registration by allowing you to define both static and dynamic rendering details in a JSON file. Here’s how to set up both static and dynamic rendering for a block using `block.json`:

### 1. Define the Block in `block.json`

Create or update your `block.json` file to include the necessary attributes for your block. Here’s an example:

{
    "apiVersion": 2,
    "name": "my-plugin/hybrid-block",
    "title": "Hybrid Block",
    "category": "widgets",
    "icon": "smiley",
    "attributes": {
        "message": {
            "type": "string",
            "default": "Hello, static content!"
        }
    },
    "editorScript": "file:./index.js",
    "renderCallback": "render_hybrid_block"
}

In this configuration:
– `"renderCallback"` is used to specify a PHP function that will handle dynamic rendering for the block on the front end.

### 2. Create the PHP Render Callback Function

Define the PHP callback function to handle dynamic rendering. This function will be registered automatically when you load `block.json`, but you’ll need to implement the logic in PHP.

In `functions.php` or your custom plugin:

function render_hybrid_block( $attributes ) {
    // Dynamic part (server-rendered)
    $dynamic_content = '<p>Dynamic time: ' . date( 'H:i:s' ) . '</p>';

    // Static part (from attributes)
    $static_content = '<p>Static message: ' . esc_html( $attributes['message'] ) . '</p>';

    return $dynamic_content . $static_content;
}

This combines both static and dynamic parts on the front end.

### 3. Create the Block’s JavaScript (Editor-Side) – `index.js`

In `index.js`, define how the block appears in the editor. Since we’re using attributes, you can set up an editable field for the `message` attribute, which will be saved statically but rendered with dynamic content in PHP.

import { useBlockProps, RichText } from '@wordpress/block-editor';

wp.blocks.registerBlockType('my-plugin/hybrid-block', {
    edit: (props) => {
        const { attributes, setAttributes } = props;
        const blockProps = useBlockProps();

        return (
            <div {...blockProps}>
                <RichText
                    tagName="p"
                    value={attributes.message}
                    onChange={(value) => setAttributes({ message: value })}
                    placeholder="Enter a message..."
                />
                <p>Dynamic content will appear here on the front end.</p>
            </div>
        );
    },
    save: () => null, // Save function is not needed as PHP handles rendering
});

### 4. Enqueue Scripts and Register the Block

Ensure your scripts are enqueued properly. When using `block.json`, WordPress should automatically load the block as long as the paths to the scripts are correct.

### Summary

With `block.json`, you streamline the configuration:
– Use `renderCallback` in `block.json` to define dynamic server-side rendering.
– Use `index.js` to set up the editor-side appearance and manage static attributes.

This setup combines static content from the editor with dynamic server-rendered content on the front end.

User
we using create block structure
Assistant
User is using the `@wordpress/create-block` structure for their WordPress blocks.
Assistant
Using the `@wordpress/create-block` structure with `block.json` simplifies the setup for both static and dynamic rendering in WordPress blocks. Here’s how to set up a block with both static and dynamic elements using this structure:

### Step 1: Generate the Block

If you haven’t created the block yet, you can generate it using:

npx @wordpress/create-block my-hybrid-block

This will create a block folder with the necessary `block.json`, PHP, JavaScript, and CSS files in the recommended WordPress format.

### Step 2: Configure `block.json` for Dynamic Rendering

In the `block.json` file, specify the render callback so that WordPress uses a PHP function to render the block dynamically on the front end.

Example `block.json` configuration:

{
    "apiVersion": 2,
    "name": "my-plugin/my-hybrid-block",
    "title": "My Hybrid Block",
    "category": "widgets",
    "icon": "smiley",
    "attributes": {
        "message": {
            "type": "string",
            "default": "This is static content!"
        }
    },
    "editorScript": "file:./build/index.js",
    "renderCallback": "my_plugin_render_hybrid_block"
}

### Step 3: Implement the PHP Render Callback Function

In the `my-hybrid-block.php` file created by `@wordpress/create-block`, add the PHP function that handles dynamic rendering. This function combines static content from attributes with server-side dynamic content.

function my_plugin_render_hybrid_block( $attributes ) {
    // Static content from attributes
    $static_content = '<p>' . esc_html( $attributes['message'] ) . '</p>';

    // Dynamic content (server-rendered)
    $dynamic_content = '<p>Current Time: ' . date( 'H:i:s' ) . '</p>';

    return $static_content . $dynamic_content;
}

add_action( 'init', function() {
    register_block_type( __DIR__ . '/build' );
} );

### Step 4: Create the Block’s Editor-Side JavaScript (`src/index.js`)

In the `src/index.js` file, configure the block’s editor appearance. The editor will allow users to enter the static message, which is saved in `message` and displayed along with a note about the dynamic content.

import { useBlockProps, RichText } from '@wordpress/block-editor';

wp.blocks.registerBlockType('my-plugin/my-hybrid-block', {
    edit: ({ attributes, setAttributes }) => {
        const { message } = attributes;
        const blockProps = useBlockProps();

        return (
            <div {...blockProps}>
                <RichText
                    tagName="p"
                    value={message}
                    onChange={(newMessage) => setAttributes({ message: newMessage })}
                    placeholder="Enter your message here..."
                />
                <p>Dynamic content will display here on the front end.</p>
            </div>
        );
    },
    save: () => null // No save function, as PHP handles rendering
});

### Step 5: Build the JavaScript and CSS

Run the following command to bundle your JavaScript and CSS files:

npm run build

This will generate the `build` folder, containing the bundled files ready for WordPress.

### Step 6: Test the Block

Add your block in the editor to test it:
– In the editor, you’ll see the static message input.
– On the front end, both the static message and dynamic server-rendered content (like the current time) will display as defined in the PHP render callback.

This setup combines the convenience of the `@wordpress/create-block` structure with flexible dynamic rendering!

User
do not use render.php
Assistant
User is not using `render.php` in their WordPress block setup.
Assistant
If you’re not using `render.php` and want to handle dynamic and static rendering directly within the structure created by `@wordpress/create-block`, you can achieve this by defining your dynamic rendering directly in the block’s PHP file without using a separate render file. Here’s how to set it up:

### Step 1: Configure `block.json`

In your `block.json` file, you specify the block details and the PHP render callback. Ensure you have it set up correctly:

{
    "apiVersion": 2,
    "name": "my-plugin/my-hybrid-block",
    "title": "My Hybrid Block",
    "category": "widgets",
    "icon": "smiley",
    "attributes": {
        "message": {
            "type": "string",
            "default": "This is static content!"
        }
    },
    "editorScript": "file:./build/index.js",
    "renderCallback": "my_plugin_render_hybrid_block"
}

### Step 2: Implement the Render Callback in the Main PHP File

In the main PHP file created by `@wordpress/create-block` (usually named something like `my-hybrid-block.php`), you will define the render callback function that will generate both static and dynamic content without needing a separate `render.php` file.

Here's how you can do it:

// Hook into WordPress to register the block type
add_action('init', function() {
    // Register the block using block.json
    register_block_type(__DIR__ . '/build');
});

// Define the render callback function
function my_plugin_render_hybrid_block($attributes) {
    // Get the static message from the attributes
    $static_content = '<p>' . esc_html($attributes['message']) . '</p>';

    // Generate dynamic content
    $dynamic_content = '<p>Current Time: ' . esc_html(date('H:i:s')) . '</p>';

    // Return combined content
    return $static_content . $dynamic_content;
}

### Step 3: Implement the Editor Script in JavaScript

In your `src/index.js` file, implement the block editor UI. This is where users will be able to input the static message that gets saved in the block’s attributes.

Here’s how to set it up:

import { useBlockProps, RichText } from '@wordpress/block-editor';

wp.blocks.registerBlockType('my-plugin/my-hybrid-block', {
    edit: ({ attributes, setAttributes }) => {
        const { message } = attributes;
        const blockProps = useBlockProps();

        return (
            <div {...blockProps}>
                <RichText
                    tagName="p"
                    value={message}
                    onChange={(newMessage) => setAttributes({ message: newMessage })}
                    placeholder="Enter your message here..."
                />
                <p>Dynamic content will display here on the front end.</p>
            </div>
        );
    },
    save: () => {
        return null; // No static save output, PHP handles rendering
    }
});

### Step 4: Build the JavaScript Files

Run the following command to build your JavaScript files:

npm run build

### Step 5: Test Your Block

1. **Add the Block in the Editor**: Open the WordPress editor and add your new block.
2. **Enter a Static Message**: Use the editor interface to input a static message.
3. **View on the Front End**: When you view the post/page, it will render both the static message and the dynamic content (like the current time).

### Summary

By directly implementing the render callback in the main PHP file and defining everything within the `@wordpress/create-block` structure, you maintain a clean and organized setup without needing a separate `render.php` file. This allows for both static and dynamic rendering seamlessly integrated within your block.

Leave a Comment

Your email address will not be published. Required fields are marked *