Voxel Mods: Trim Post Content by Heading Range

This modifier enables you to trim the content of a Gutenberg WordPress post by specifying a range of heading blocks. Within the defined range, it also includes any non-heading content such as paragraphs, images, and buttons.

The code counts the Core/Heading blocks from a Gutenberg post, Generateblocks/Headline from GenerateBlocks, and Kadence/Advancedheading from Kadence Blocks. Other 3rd party block plugins may not work.

Working with:

  • Core Gutenberg
  • GenerateBlocks
  • Kadence Blocks

Use Case

This Voxel Mod is particularly useful for inserting ads or banners after a specific number of headings (and their associated content) within a single post template.

For instance, after the third heading, you can place a banner or call-to-action (CTA) by setting the start heading to 0 (the beginning of the post) and the end heading to 3 (and its following non-heading content).

Noe: You must use @post(content), not @post(:content). ie. the dynamic tag must not have the colon (:).

To achieve this, you’ll need two or more Text Editor widgets in your post template, each configured with a different range of the post content.

The CTA can then be added between these Text Editor widgets. The post will continue seamlessly by setting the start heading to 4 and leaving the end heading field blank, displaying all content from heading 4 to the end of the post.

Benefits

This method offers a flexible and dynamic way to structure your content, allowing for programmatic ad insertions exactly where you want them. It ensures a smooth and uninterrupted user experience while optimizing space for advertisements or promotional banners.

Heading Number Inputs:

Start Heading (0 for start): This input defines the starting point for the content you want to display:

  • 0 means the modifier will start from the very beginning of the post, including any content before the first heading (like images, paragraphs, or other blocks).
  • 1 means the modifier will start from the first heading block.
  • 2 means the modifier will start from the second heading block, and so on.

End Heading (leave blank for end): This input defines the endpoint for the content you want to display:

  • If you leave this field blank, the content will continue until the end of the post, including all headings and other elements that follow.
  • If you specify a number, the modifier will stop the content display at the specified heading block and will include any non-heading HTML content that follows. For example, if you specify end = 2, it will show all content grouped under heading 2, until the next available heading.

*** Notice this CTA banner is injected after the 3rd heading’s content on all articles. Voxel Mods! ***

Unleash Dynamic Data with Voxel!

With Voxel’s design flexibility, the possibilities are endless. Get Voxel here!

Examples:

Display content from the beginning of the post to the 1st heading

  • Start Heading: 0
  • End Heading: 1
  • This will display everything from the start of the post, including any elements like images, paragraphs, or blocks, up to and including the 1st heading and will include any non-heading HTML content that follows.

Display content grouped under the 2nd heading

  • Start Heading: 2
  • End Heading: 2
  • This will display all content from the 2nd heading and will include any non-heading content (images, paragraphs, or other blocks) that follows, up to the next heading’s start (up to heading 3 in this case).

Display content from the 3rd heading to the 4th heading

  • Start Heading: 3
  • End Heading: 4
  • This will display all content starting from the 3rd heading up until and including the 4th heading block and will include any content (images, paragraphs, or other blocks that follow up to heading 5).

Display content starting from the 5th heading to the end of the post

  • Start Heading: 5
  • End Heading: (leave blank)
  • This will display everything starting from the 5th heading block and continuing until the end of the post, including all other elements like paragraphs, images, and buttons.

Conclusion:

This modifier gives you precise control over which sections of a post to display, and which sections to add a section break so you can insert your templated content within the post data.

The Code: Voxel Theme Modifier: Trim Post by Heading Range

*** Disclaimer – Use at your own risk. Always make a backup. ***

Add to your child theme’s functions.php file.

add_filter( 'voxel/dynamic-data/modifiers', function( $modifiers ) {
    class Trim_Post_By_Heading_Range extends \Voxel\Dynamic_Data\Modifiers\Base_Modifier {
        public function get_label(): string {
            return 'Trim Post by Heading Range';
        }

        public function get_key(): string {
            return 'trim_post_by_heading_range';
        }

        protected function define_args(): void {
            $this->define_arg( [
                'type' => 'text',
                'label' => _x( 'Start Heading (0 for start)', 'modifiers', 'voxel-backend' ),
            ] );

            $this->define_arg( [
                'type' => 'text',
                'label' => _x( 'End Heading (leave blank for end)', 'modifiers', 'voxel-backend' ),
            ] );
        }

        public function apply( string $value ) {
            // Ensure we're working with the post content (get_the_content())
            $post_content = get_the_content();

            // If the content is empty or not available, return an empty string
            if ( empty( $post_content ) ) {
                return '';
            }

            // Parse the blocks from the post content
            $blocks = parse_blocks( $post_content );

            // Get the start and end heading indices
            $start_heading = absint( $this->get_arg(0) ?: 0 );
            $end_heading = $this->get_arg(1) !== '' ? absint( $this->get_arg(1) ) : PHP_INT_MAX;

            $current_heading_count = 0;
            $trimmed_blocks = [];

            foreach ( $blocks as $block ) {
                // Check if the block is a heading (core, GenerateBlocks, or Kadence Blocks)
                if ( 
                    $block['blockName'] === 'core/heading' || 
                    $block['blockName'] === 'generateblocks/headline' || 
                    $block['blockName'] === 'kadence/advancedheading' 
                ) {
                    $current_heading_count++;
                }

                // Respect the start heading even if end heading is blank
                if ( $current_heading_count >= $start_heading && $current_heading_count <= $end_heading ) {
                    $trimmed_blocks[] = $block;
                }

                // Stop processing if we've passed the end range
                if ( $current_heading_count > $end_heading ) {
                    break;
                }
            }

            // Rebuild content from the selected blocks
            $output = '';
            foreach ( $trimmed_blocks as $block ) {
                // Render block content using WordPress filters
                $output .= apply_filters( 'the_content', render_block( $block ) );
            }

            // Escape the output to prevent XSS but allow valid HTML content
            return wp_kses_post( $output );
        }
    }

    $modifiers['trim_post_by_heading_range'] = \Trim_Post_By_Heading_Range::class;
    return $modifiers;
} );

To implement this solution, you’ll need to add the code to your WordPress site. You have two options for where to place this code:

  • Child Theme’s functions.php File:

    If you’re already using a child theme (recommended for customization), simply add the PHP code to your functions.php file. This will ensure your changes are preserved even if the main Voxel theme is updated.

  • Code Snippets Plugin:

    If you prefer not to edit theme files directly, or if you want to manage your custom code more easily, you can use the Fluent Snippets plugin. This plugin allows you to add custom PHP code without touching your theme files. Just create a new function.php snippet, paste the code, and activate it.

Then apply this Voxel Mod from the Elementor builder interface.

More Articles

Keeping track of price changes can be essential for various use cases, whether you’re running a marketplace, showcasing products, or simply maintaining historical price records. In this guide, we will walk you through a practical solution to automatically track price changes on your WordPress site using the Voxel theme and a custom code snippet. By […]
Voxel Price Changes
The Voxel Theme and Crocoblock are both powerful solutions for building complex, dynamic websites on WordPress. Let’s explore their features, pricing, and unique selling points to help you make an informed decision. Pricing Feature Comparison Feature Voxel Crocoblock Custom Post Types and Fields Visually create and manage WordPress Post types, Meta fields, Taxonomies JetEngine allows […]
Voxel vs Crocoblock: A Comprehensive Comparison

Support me

Coffee is my fuel

All guides are available for FREE.

If this saved you time, please support my work by checking out the recommended tools or buying me a coffee.