php max excerpt length not must length (exclude html / css)

I have a problem using the below:

<?php echo excerpt(15); ?>

Because! I have some pages (unfortunately) that have on-page styles and little text, not meeting the 15 characters, so what is occurring is the excerpt limit is not being met, so it displays ‘a little text.. then <css> <styles><h1> <h2>, etc’.

Read More

How can I re-write as UP to 15 character limit, or MAX. So if it falls short that’s fine. Or to exclude HTML / and CSS?


Excerpt function within functions.php

function excerpt($limit) {
      $excerpt = explode(' ', get_the_excerpt(), $limit);
      if (count($excerpt)>=$limit) {
        array_pop($excerpt);
        $excerpt = implode(" ",$excerpt).'...';
      } else {
        $excerpt = implode(" ",$excerpt);
      } 
      $excerpt = preg_replace('`[[^]]*]`','',$excerpt);
      return $excerpt;
    }

    function content($limit) {
      $content = explode(' ', get_the_content(), $limit);
      if (count($content)>=$limit) {
        array_pop($content);
        $content = implode(" ",$content).'...';
      } else {
        $content = implode(" ",$content);
      } 
      $content = preg_replace('/[.+]/','', $content);
      $content = apply_filters('the_content', $content); 
      $content = str_replace(']]>', ']]&gt;', $content);
      return $content;
    }

remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'custom_trim_excerpt');

function custom_trim_excerpt($text) { // Fakes an excerpt if needed
global $post;
if ( '' == $text ) {
$text = get_the_content('');
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$text = strip_tags($text);
$excerpt_length = 35;
$words = explode(' ', $text, $excerpt_length + 1);
if (count($words) > $excerpt_length) {
array_pop($words);
array_push($words, '...');
$text = implode(' ', $words);
}
}
return $text;
}

Related posts

Leave a Reply

1 comment

  1. You have three options (possibly more, this isn’t meant to be exhaustive)

    1. Abandon the wordpress function. By using custom PHP passing the $post->post_content through to your own function you could use PHP’s XML manipulation functions, specifically DOM manipulation, or a regular expression to remove certain tags.

    2. Do a check on your post content before running excerpt. If you can check for the existence of a tag to start within the first 15 characters by checking for the first position of a “<” character using strpos, then you can use a normal if/else.

    3. Using wordpresses functionality properly, you can change how the excerpt is dealt with through filters. You can remove the default functionality and replace it with your own. This link in particular is very useful for explaining how to customise your excerpt function in wordpress, specifically with regards to allowing tags or not within the excerpt.