Last active
November 21, 2023 16:40
-
-
Save pdclark/95fc9a568ea5d3054b8dae1765726232 to your computer and use it in GitHub Desktop.
The shortest possible example PHP-rendered WordPress block.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
); |
ducktype
commented
Nov 21, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment