Answers for "Gutenberg block server side rendering"

PHP
0

Gutenberg block server side rendering

import { registerBlockType } from '@wordpress/blocks';
import ServerSideRender from '@wordpress/server-side-render';
import { useBlockProps } from '@wordpress/block-editor';
 
registerBlockType( 'gutenberg-examples/example-dynamic', {
    apiVersion: 2,
    title: 'Example: last post',
    icon: 'megaphone',
    category: 'widgets',
 
    edit: function ( props ) {
        const blockProps = useBlockProps();
        return (
            <div { ...blockProps }>
                <ServerSideRender
                    block="gutenberg-examples/example-dynamic"
                    attributes={ props.attributes }
                />
            </div>
        );
    },
} );
Posted by: Guest on June-05-2021
0

Gutenberg block server side rendering

<?php
 
/**
 * Plugin Name: Gutenberg examples dynamic
 */
 
function gutenberg_examples_dynamic_render_callback( $block_attributes, $content ) {
    $recent_posts = wp_get_recent_posts( array(
        'numberposts' => 1,
        'post_status' => 'publish',
    ) );
    if ( count( $recent_posts ) === 0 ) {
        return 'No posts';
    }
    $post = $recent_posts[ 0 ];
    $post_id = $post['ID'];
    return sprintf(
        '<a class="wp-block-my-plugin-latest-post" href="%1$s">%2$s</a>',
        esc_url( get_permalink( $post_id ) ),
        esc_html( get_the_title( $post_id ) )
    );
}
 
function gutenberg_examples_dynamic() {
    // automatically load dependencies and version
    $asset_file = include( plugin_dir_path( __FILE__ ) . 'build/index.asset.php');
 
    wp_register_script(
        'gutenberg-examples-dynamic',
        plugins_url( 'build/block.js', __FILE__ ),
        $asset_file['dependencies'],
        $asset_file['version']
    );
 
    register_block_type( 'gutenberg-examples/example-dynamic', array(
        'api_version' => 2,
        'editor_script' => 'gutenberg-examples-dynamic',
        'render_callback' => 'gutenberg_examples_dynamic_render_callback'
    ) );
 
}
add_action( 'init', 'gutenberg_examples_dynamic' );
Posted by: Guest on June-05-2021

Code answers related to "Gutenberg block server side rendering"

Browse Popular Code Answers by Language