Created
January 6, 2015 16:40
-
-
Save strangerstudios/25fc2454f5d3e483af8b to your computer and use it in GitHub Desktop.
Filter to add drop caps to first letter of blog posts in WordPress. Add to your active theme's functions.php.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Drop cap first letter of each post. | |
*/ | |
function add_drop_caps($content) | |
{ | |
global $post; | |
//only posts | |
if(!empty($post) && $post->post_type == "post") | |
{ | |
//find first p tag with a letter following it | |
$match = getMatches("/\<p\>[A-Z]/i", $content, true); | |
if(!empty($match)) | |
{ | |
$letter = str_replace("<p>", "", $match); | |
$dropcap = '<p><span class="dropcap">' . $letter . '</span>'; | |
$content = str_replace_once($match, $dropcap, $content); | |
} | |
} | |
return $content; | |
} | |
add_filter('the_content', 'add_drop_caps', 30); | |
add_filter('the_excerpt', 'add_drop_caps', 30); | |
/* | |
Helper for Getting RegExp Matches | |
*/ | |
function getMatches($p, $s, $firstvalue = FALSE, $n = 0) | |
{ | |
$ok = preg_match_all($p, $s, $matches); | |
if(!$ok) | |
return false; | |
else | |
{ | |
if($firstvalue) | |
return $matches[$n][0]; | |
else | |
return $matches[$n]; | |
} | |
} | |
/* | |
Replace a string once. | |
From: http://php.net/manual/en/function.str-replace.php#86177 | |
*/ | |
function str_replace_once($search, $replace, $subject) { | |
$firstChar = strpos($subject, $search); | |
if($firstChar !== false) { | |
$beforeStr = substr($subject,0,$firstChar); | |
$afterStr = substr($subject, $firstChar + strlen($search)); | |
return $beforeStr.$replace.$afterStr; | |
} else { | |
return $subject; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is going to fail if a post starts with a quotation mark, newline, parenthesis, Spanish ¡ character, etc.