Skip to content

Snippet: Custom Blog Entry Blocks/Sections & Output

If you are using a page builder such as WPBakery, Elementor or Gutenberg we recommend using a Dynamic Template for customizing your post design rather then adding custom blocks.

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. It also allows you to override any of the default "blocks" with your custom output!

/**
 * Add a new custom block option to the blog entry blocks.
 *
 * @link https://total.wpexplorer.com/docs/snippets/custom-blog-entry-blocks/
 */
add_filter( 'totaltheme/blog/entry_blocks/choices', function( $blocks ) {
    $blocks['new_block_id'] = __( 'New block', 'wpex' );
    return $blocks;
} );

/**
 * Render our custom blog entry blocks.
 *
 * @link https://total.wpexplorer.com/docs/snippets/custom-blog-entry-blocks/
 */
add_filter( 'totaltheme/blog/entry_blocks', function( $blocks ) {

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

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

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

	// Example 4: Override the default featured_media block
	if ( isset( $blocks['featured_media'] ) ) {
		$blocks['featured_media'] = function() {
			echo 'My custom featured media';
		};
	}

	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