Add span to the first letter of post

Example post

<p>Lorem ipsum dolor sit amet</p>
<p>Morbi elementum odio vel tortor adipiscing vel tempor risus ullamcorper.</p>

What I have done :

function first_paragraph($content){
    return preg_replace('/<p([^>]+)?>/', '<p$1 class="first-paragraph">', $content, 1);
}
add_filter('the_content', 'first_paragraph');

Which will have different class for first paragraph

Now I want add <span class="first-letter">L</span> and result should be like

<p class="first-paragraph"><span class="first-letter">L</span>orem ipsum dolor sit amet</p>
<p>Morbi elementum odio vel tortor adipiscing vel tempor risus ullamcorper.</p>

Let me know


Update:

I got it worked but not a perfect solution.

function first_paragraph($content){
    $content = substr_replace($content, '</span>', 4, 0);
    $content = substr_replace($content, '<span class="first-letter">', 3, 0);
    $content = preg_replace('/<p([^>]+)?>/', '<p$1 class="first-paragraph">', $content, 1); 
return $content;
}
add_filter('the_content', 'first_paragraph');

1 Answer
1

This drop caps plugin does what you are looking for: http://wordpress.org/extend/plugins/drop-caps/

If you’re trying to do drop caps this should be enough. If you want to do more you could look into the code and see how the plugin wraps the 1st char in a span. It probably uses preg replace too. Id look myself but I’m answering this on my phone and have no way of looking at the code.

Leave a Comment