Created
June 29, 2017 04:51
-
-
Save kosinix/03b65c1591d0f17150537443b1496a70 to your computer and use it in GitHub Desktop.
Read more that ends in sentence or exact words.
This file contains hidden or 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 | |
add_filter( 'the_content', 'my_the_content_filter', 22 ); | |
function my_the_content_filter( $content ) { | |
if ( is_home() || is_archive() || is_search() ){ | |
// Mode word | |
$mode = 'sentence'; // word or sentence | |
$count = 11; | |
// Let WP do its thing | |
$trimmed = wp_trim_words( | |
$content, | |
1000000, | |
'' | |
); | |
// Split trimmed content into x number of words | |
$words = explode(' ', $trimmed); | |
$words = array_slice($words, 0, $count); | |
$content = implode(' ', $words); | |
if($mode==='sentence'){ | |
$pos = mb_strlen($content); // Find last word position | |
$pos = mb_strpos($trimmed, '.', $pos-1); // Find the period(.) | |
// TODO: Support other end of sentence marks like ? and ! | |
if($pos!==false){ | |
$content = mb_substr($trimmed, 0, $pos+1); // Get string until end of sentence | |
} | |
} | |
$content .= sprintf( | |
'<p><a class="btn btn-default read-more" href="%s" title="%s">%s</a></p>', | |
get_permalink(), get_the_title(), 'Read More' | |
); | |
} | |
// Returns the content. | |
return $content; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment