badcrocodile
1/5/2015 - 10:12 PM

Trim get_the_content to X number of characters, while keeping any HTML intact

Trim get_the_content to X number of characters, while keeping any HTML intact

<?php
/**
 * Trim get_the_content to X number of characters, while keeping any HTML intact
 *
 * @param int $char_count Trim to number of characters
 * @return string
 */
function get_excerpt($char_count) {
  $permalink = get_permalink($post->ID);
  $excerpt = get_the_content();
  $excerpt = preg_replace(" (\[.*?\])",'',$excerpt);
  $excerpt = strip_shortcodes($excerpt);
  $excerpt = strip_tags($excerpt);
  $excerpt = substr($excerpt, 0, $char_count);
  $excerpt = substr($excerpt, 0, strripos($excerpt, " "));
  $excerpt = trim(preg_replace( '/\s+/', ' ', $excerpt));
  $excerpt = $excerpt.'... <a href="'.$permalink.'">more</a>';
  return $excerpt;
}
?>