Skip to content

Instantly share code, notes, and snippets.

@strangerstudios
Created January 6, 2015 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save strangerstudios/25fc2454f5d3e483af8b to your computer and use it in GitHub Desktop.
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.
/*
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;
}
}
@plqu
Copy link

plqu commented Sep 16, 2023

This is going to fail if a post starts with a quotation mark, newline, parenthesis, Spanish ¡ character, etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment