skip to Main Content

Custom Blog Post Blocks & Rendering

This is very similar to the snippet example here here but it allows you to have a custom output function rather then creating a template part.

/**
 * Register a blog post "block" which we can then enable in the Customizer.
 *
 * @link https://total.wpexplorer.com/docs/snippets/custom-blog-single-block/
 */
function my_add_new_block( $blocks ) {
	$blocks['new_block_id'] = __( 'New Block Name', 'textdomain' );
	return $blocks;
}
add_filter( 'wpex_blog_single_blocks', 'my_add_new_block' );

/**
 * Renders our custom blog post blocks.
 *
 * @link https://total.wpexplorer.com/docs/snippets/custom-blog-single-block/
 */
function my_new_block_output( $blocks ) {

	// Before defining the output we want to make sure the block is enabled in the Customizer.
	if ( isset( $blocks[ 'new_block_id' ] ) ) {

		// Example 1: Add new block with an anonymous function for the output.
		$blocks['new_block_id'] = function() {
			echo 'test';
		};

		// Example 2: Add new block with a custom function as the output
		$blocks['new_block_id'] = my_function_name();

		// Example 3: Add new block with an anonymous function that returns a template part
		$blocks['new_block_id'] = function() {
			get_template_part( 'my-custom-block-file' );
		};

	}

	return $blocks;
}
add_filter( 'wpex_blog_single_layout_blocks', 'my_new_block_output' );
All PHP snippets should be added via child theme's functions.php file or via a plugin (we recommend Code Snippets)
Back To Top