How to Create Drop Cap to WordPress Post without Plugin

A drop cap is the first letter of a paragraph that’s of a much bigger size than the rest that follow. The letter formatting is such that the letter “˜drops down’ to cover the few lines following the first one.

We can create the drop cap to by giving some styles to first letter of the post. But first we have to give a class to that first letter so we can give it the style. actually, There is a css selector for first letter. You can read a drop cap tutorial here:link. Unfortunately, the selector doesn’t work in old browser. Yes, some users are still using ie6 :)

drop cap wordpress

Here’s the script to add a class to first letter of the post. Simply put the code to your theme function.php


function post_first_letter($content = '') {
		$pattern = '/<p( .*)?( class="(.*)")??( .*)?>((|\s)*)(("|“|‘|‘|“|\')?[A-Z])/U';
		$replacement = '<p><span title="$7" class="post-first-letter">$7</span>';
		$content = preg_replace($pattern, $replacement, $content, 1 );

	return $content;
}
		
add_filter('the_content', 'post_first_letter');

Now, the first letter comes with post-first-letter class, which you can add your drop cap style.
Here’s example style that You can place in the theme style.css file

.post-first-letter {
font-size: 50px;
float: left;
margin-top: 14px; 
margin-right: 5px;
}

Credit:
The code is taken from : drop cap plugin

8 Comments to “How to Create Drop Cap to WordPress Post without Plugin”

Add Comments (+)

  1. Nicolas says:

    Woudn’t be simpler to use css3?

  2. Its well explained tutorial. You have post a nice article.

  3. Jason Pelker says:

    This current code makes any images you have at the top of your post disappear. What might be needed to allow for both images and drop caps?

  4. Tony says:

    Same problem with Pelker.
    Cant use this code.

  5. Rico says:

    I changed the code on my blog (I use images).

    $pattern = ‘/((]*>|\s)*)(("|“|‘|‘|“|\’)?[A-Z])/U’;
    $replacement = ‘$5$7′;
    $content = preg_replace($pattern, $replacement, $content, 1 );

    Hope it helps.

  6. Philippe says:

    Thanks for the trick.
    I’ve changed the css to fit my needs and it works fine.

    Here is my css :

    .post-first-letter { float: left; font-family: Georgia,serif; font-size: 4em; font-weight: bold; line-height: 0.85em; margin-bottom: -0.25em; margin-right: 3px; }

Trackbacks/Pingbacks

  1. Must Read Links for Web Designers and Developers – Volume 10 | Tech King
  2. Tự động viết hoa chữ cái đầu tiên trong bài viết không cần plugin | Quý Xuân Blog

Leave a Reply

 

Amazingly Beautiful WordPress Themes