THE PENDING DRAFT

Adding things to titles inside the post content

January 8, 2015

For a specific styling i needed to be able to add elements, specifically a <span> element inside the H2 tags automatically.

Outside of the content is easy

To achieve this for titles outside of the_content is pretty easily done with the $before and $after Parameters on the_title() like so, or we could just wrap the_title inside the desired tags.

<?php the_title( '<h2 class="entry-title"><span>', '</span></h2>' ); ?>

Filtering the_content

To achieve the same result for all H2 tags inside the content we need to filter the_content with a regular expression.

function pdr_add_class_to_h2( $content ){
    return preg_replace( '/<h2(.*?)>(.*?)<\/h2>/', '<h2\1 class="entry-title"><span>\2</span></h2>', $content );
}
add_filter( 'the_content', 'pdr_add_class_to_h2' );

To extend this with other tags to replace, we can also pass arrays to preg_replace. Each element in $pattern will be replace by its counterpart in $replacement.

function pdr_add_class_to_titles( $content ){

    $pattern = array(
        '/<h2(.*?)>(.*?)<\/h2>/',
        '/<h3(.*?)>(.*?)<\/h3>/',
        '/<h4(.*?)>(.*?)<\/h4>/',
        '/<h5(.*?)>(.*?)<\/h5>/',
        '/<h6(.*?)>(.*?)<\/h6>/'
    );

    $replacement = array(
        '<h2\1 class="entry-title"><span>\2</span></h2>',
        '<h3\1 class="entry-title"><span>\2</span></h3>',
        '<h4\1 class="entry-title"><span>\2</span></h4>',
        '<h5\1 class="entry-title"><span>\2</span></h5>',
        '<h6\1 class="entry-title"><span>\2</span></h6>',
    );

return preg_replace( $pattern, $replacement, $content );
}
add_filter( 'the_content', 'pdr_add_class_to_titles' );

I found this solution in this support thread and adapted it a bit to fit my needs and replace all titles but it could basically be used to replace all kinds of stuff inside the content.

Leave your comment