Modify post content to insert text after h2

This code snippet filters the_content(), uses regex to find the first h2 and insert content from an ACF custom field named affiliate_text from the options page.

/**
 * Custom function to modify the post content by inserting text after the first <h2> tag.
 *
 * @param string $content The original post content.
 * @return string Modified post content.
 */
function affiliate_h2($content) {
    global $post;

    // Check if we are on a single post/page and if the post content is not empty
    if (is_single() && !empty($content)) {
        // Retrieve the custom field value
        $custom_field_value = get_field('affiliate_text', 'option');
        
        // Use regex to find the first <h2> tag
        $pattern = '/<h2[^>]*>.*?<\/h2>/i';
        preg_match($pattern, $content, $matches);

        // Check if an <h2> tag was found
        if (!empty($matches)) {
            // Create a paragraph tag with the custom field value
            $custom_paragraph = '<p>' . $custom_field_value . '</p>';

            // Insert the custom paragraph before the first <h2> tag
            $content = preg_replace($pattern, $custom_paragraph . '$0', $content, 1);
        }
    }

    return $content;
}
// Hook the custom function to the_content filter
add_filter('the_content', 'affiliate_h2');

Leave a Reply

Your email address will not be published. Required fields are marked *