Example shortcode for serverside rendering and interactivity using HTMXpress. Based on Htmx serverside block example.
Requires HTMXPress plugin being installed and active.
After installing this plugin, include the shortcode in template using [htmx_shortcode]
.
The htmx_shortcode_function
function simply includes a template:
'render_callback' => function () {
ob_start();
load_template( __DIR__ . '/templates/random_posts.php' );
return ob_get_clean();
},
The plugin's templates are registered with HTMXpress, this makes them available under the /htmx/
endpoint:
# register plugin's templates, which adds them to the /htmx endpoint.
add_filter( 'htmx.template_paths', static function ( $paths ) {
$paths[] = __DIR__ . '/templates';
return $paths;
} );
The templates/random_posts.php template contains a WP_Query to load 3 random posts and a button which refreshes only the posts:
echo '<button hx-post="/htmx/random_posts" hx-target="#random-posts"> More </button>';