Conditional Output in Bricks based on if Content has Headings

If you have a section in your single post template having a dynamically generated TOC from headings but do not want it to be output if there are no headings, this Pro tutorial shows how.

Step 1

Add the following in child theme‘s functions.php (w/o the opening PHP tag) or a code snippets plugin:

<?php

/**
 * Check if the current post content has h2, h3, or h4 headings.
 *
 * @return bool True if the post content has h2, h3, or h4 headings, false otherwise.
 */
function bl_has_content_headings(): bool {
    // Get the current post content
    $content = get_the_content();

    // Remove any potential shortcodes to avoid false positives
    $content = strip_shortcodes( $content );

    // Remove any potential scripts and styles to avoid false positives
    $content = preg_replace( '/<scriptb[^>]*>(.*?)</script>/is', '', $content );
    $content = preg_replace( '/<styleb[^>]*>(.*?)</style>/is', '', $content );

    // Regular expression pattern to match h2, h3, or h4 tags
    $pattern = '/<h[234][^>]*>.*?</h[234]>/i';

    // Check if the pattern matches the content
    return (bool) preg_match( $pattern, $content );
}

Step 2

Whitelist the bl_has_content_headings function.

Ex.:

<?php 

add_filter( 'bricks/code/echo_function_names', function() {
  return [
    'bl_has_content_headings'
  ];
} );

You should also add other functions (native or custom) being used in your Bricks instance besides bl_has_content_headings. This can be checked at Bricks → Settings → Custom code by clicking the Code review button.

More info on whitelisting can be found here.

Step 3

In your single post template, now you are ready to use the above function in a dynamic data condition.

{echo:bl_has_content_headings}

Any element with the above condition applied will only be output if that single post has h2 or h3 or h4 headings.

Credit

AI.