I'm trying to insert a div with a small bit of content immediately after the /h2 of single posts. I've given single posts a new class to help trigger this, as I don't want it after the /h2 on a page. I think I need to filter the content but am not sure how to write this function. Any help appreciated. Thanks.

1 Answer 1


You're right, you can do that with a filter (the_content). I attached an example. You can put that into the functions.php of your theme.

function add_content_after_h2($content){
    if (is_single()) {
        $div = '<div>small bit of content</div>';
        $content = preg_replace('/(<\/h2>)/i', '\1'.$div, $content);

    return $content;

add_filter('the_content', 'add_content_after_h2');

Here you find the Wordpress Codex with a detailed description of that filter: https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.