Last active
January 18, 2019 21:59
-
-
Save adamcapriola/f466670fcb88efb2ca8060e79fdb1904 to your computer and use it in GitHub Desktop.
Automatically Bold (or Style) the First X Words of Content
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
<?php | |
/** | |
* Lede words | |
* | |
*/ | |
add_filter( 'the_content', 'ac_the_content_lede_words' ); | |
function ac_the_content_lede_words( $content ) { | |
// Get number of lede words | |
$lede_words = (int) get_post_meta( get_the_ID(), '_lede_words', true ); // Create metabox for this or manually save custom field value, and adjust key if necessary | |
// Bail: Zero lede words | |
if ( 0 === $lede_words ) { | |
return $content; | |
} | |
// Include trailing comma | |
$trailing_comma = true; // Set false to exclude trailing comma from lede words | |
$comma = ( false === $trailing_comma ) ? ',' : ''; | |
// Expressions | |
$first = $second = $third = ''; | |
switch ( $lede_words ) { | |
case 1: | |
$first = '[^\s<' . $comma . ']+'; | |
break; | |
case 2: | |
$first = '[^\s<]+'; | |
$third = '\s+[^\s' . $comma . ']+'; | |
break; | |
case 3: | |
default: | |
$first = '[^\s<]+'; | |
$second = '\s+[^\s]+'; | |
$third = '\s+[^\s' . $comma . ']+'; | |
} | |
// More than three lede words | |
while ( $lede_words > 3 ) { | |
// Repeat the second expression | |
$second .= '\s+[^\s]+'; | |
$lede_words--; | |
} | |
// Replace | |
$content = preg_replace( '/<p>(' . $first . $second . $third . ')/', '<p><span class="lede-words">$1</span>', $content, 1 ); | |
return $content; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment