Skip to content

Snippet: 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://totalwptheme.com/docs/snippets/custom-blog-single-block/
 */
add_filter( 'totaltheme/blog/single_blocks/choices', function( $blocks ) {
	$blocks['new_block_id'] = __( 'New Block Name', 'textdomain' );
	return $blocks;
} );

/**
 * Renders our custom blog post blocks.
 *
 * @link https://totalwptheme.com/docs/snippets/custom-blog-single-block/
 */
add_filter( 'totaltheme/blog/single_blocks', function( $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;
} );
All PHP snippets should be added via child theme's functions.php file or via a plugin.
We recommend Code Snippets (100% Free) or WPCode (sponsored)
Back To Top