1<?php
2
3/**
4 * Plugin Name: Gutenberg examples dynamic
5 */
6
7function gutenberg_examples_dynamic_render_callback( $block_attributes, $content ) {
8 $recent_posts = wp_get_recent_posts( array(
9 'numberposts' => 1,
10 'post_status' => 'publish',
11 ) );
12 if ( count( $recent_posts ) === 0 ) {
13 return 'No posts';
14 }
15 $post = $recent_posts[ 0 ];
16 $post_id = $post['ID'];
17 return sprintf(
18 '<a class="wp-block-my-plugin-latest-post" href="%1$s">%2$s</a>',
19 esc_url( get_permalink( $post_id ) ),
20 esc_html( get_the_title( $post_id ) )
21 );
22}
23
24function gutenberg_examples_dynamic() {
25 // automatically load dependencies and version
26 $asset_file = include( plugin_dir_path( __FILE__ ) . 'build/index.asset.php');
27
28 wp_register_script(
29 'gutenberg-examples-dynamic',
30 plugins_url( 'build/block.js', __FILE__ ),
31 $asset_file['dependencies'],
32 $asset_file['version']
33 );
34
35 register_block_type( 'gutenberg-examples/example-dynamic', array(
36 'api_version' => 2,
37 'editor_script' => 'gutenberg-examples-dynamic',
38 'render_callback' => 'gutenberg_examples_dynamic_render_callback'
39 ) );
40
41}
42add_action( 'init', 'gutenberg_examples_dynamic' );
43
1import { registerBlockType } from '@wordpress/blocks';
2import ServerSideRender from '@wordpress/server-side-render';
3import { useBlockProps } from '@wordpress/block-editor';
4
5registerBlockType( 'gutenberg-examples/example-dynamic', {
6 apiVersion: 2,
7 title: 'Example: last post',
8 icon: 'megaphone',
9 category: 'widgets',
10
11 edit: function ( props ) {
12 const blockProps = useBlockProps();
13 return (
14 <div { ...blockProps }>
15 <ServerSideRender
16 block="gutenberg-examples/example-dynamic"
17 attributes={ props.attributes }
18 />
19 </div>
20 );
21 },
22} );
23