Skip to content

Instantly share code, notes, and snippets.

@pdclark
Last active Jul 29, 2021
Embed
What would you like to do?
The shortest possible example PHP-rendered WordPress block.
<?php
/**
* Plugin Name: Block — Hi Test
* Description: The shortest possible example PHP-rendered WordPress block.
* Author: Paul Clark
* Author URI: https://pdclark.com
*
* @package hi
*/
/**
* Register: PHP.
*/
add_action(
'init',
function() {
wp_register_script(
'hi-test',
add_query_arg( [ 'action' => 'block-hi.js', ], admin_url( 'admin-ajax.php' ) ),
[ 'wp-blocks', 'wp-element', 'wp-editor' ],
microtime(),
true
);
register_block_type(
'hi/test',
[
'editor_script' => 'hi-test',
'render_callback' => function( $attributes, $content ) {
ob_start();
do_action( 'hi/test/render_callback', $attributes, $content );
return ob_get_clean();
},
]
);
}
);
/**
* Render: PHP.
*
* @param array $attributes Optional. Block attributes. Default empty array.
* @param string $content Optional. Block content. Default empty string.
*/
add_action(
'hi/test/render_callback',
function( $attributes, $content ) {
?>
<h1>Hello world.</h1>
<?php
$q = new WP_Query(
[
'post_type' => 'post',
'numberposts' => 3,
]
);
while ( $q->have_posts() ) {
$q->the_post();
?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><br/>
<?php
}
wp_reset_postdata();
},
10,
2
);
/**
* Register: JavaScript.
*
* @see https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/creating-dynamic-blocks/
*/
add_action(
'wp_ajax_block-hi.js',
function() {
header( 'Content-Type: text/javascript' );
?>
( function ( blocks, element, serverSideRender, blockEditor ) {
var el = element.createElement,
registerBlockType = blocks.registerBlockType,
ServerSideRender = serverSideRender,
useBlockProps = blockEditor.useBlockProps;
registerBlockType( 'hi/test', {
apiVersion: 2,
title: 'Hi Test',
icon: 'megaphone',
category: 'widgets',
edit: function ( props ) {
var blockProps = useBlockProps();
return el(
'div',
blockProps,
el( ServerSideRender, {
block: 'hi/test',
attributes: props.attributes,
} )
);
},
} );
} )(
window.wp.blocks,
window.wp.element,
window.wp.serverSideRender,
window.wp.blockEditor
);
<?php
exit;
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment