I've been struggling with this for a long time... I want to limit article lenght to 100 characters and after 100 char. limit, add at the end '...' linked to a single post (like wordpress's <!--more--> ). But I can't use the_excerpt becouse it removes formating (ex. <b>, <a> tags). Can somebody help me with this?

1 Answer 1

function get_custom_excerpt( $content, $link ){

   $content = some_function_to_handle_html_tag(substr($content, 0, 100)); // EDIT: need to be customized with a regex for proper output
   $content .= ' <a href="'.$link.'"> more... </a>';

   return $content;

function some_function_to_handle_html_tag(){
    //a regex to check last occurance of html opening tag
    //append respective closing tag or strip the tag if broken e.g. '<' or '<something'
//for global $post
echo get_custom_excerpt($post->post_content, get_permalink($post->ID)); //print the custom excerpt of 100 characters


//when in loop
echo get_custom_excerpt(get_the_content(), get_permalink(get_the_ID())); //print the custom excerpt of 100 characters


This could be unstable if some html tag was opened in first 100 character but not closed. I tried to figure out a proper solution (show content without stripping html) but found nothing helpful. But, I have an idea that may help -

1) You may use a regex which will check last occurance of a string which starts with < and ends with >, then you will have to add a respective closing tag in the end. So, say e.g. if there is tag <span>, the </span> will need to be added in the end to prevent html layout from breaking.

2) If any occurance like < or <something occurs, then that should be removed.

Then the above code should work for most of the cases.

  • What if you cut the content in the middle of a HTML tag? That could effect the layout of the whole page. It would be great if you could update your solution to solve that possible problem. Multibyte characters might also be a trouble here.
    – birgire
    Sep 15, 2014 at 15:04
  • It worked on the second post not on first one... What I did wrong :O ?
    – Paul
    Sep 15, 2014 at 15:26
  • This code is kinda unstable. I don't know why but after pasting it and refreshing main site it works as I wanted but when I try to edit post and publish it, everything disappears and i only see 'more ...' at the top. :(
    – Paul
    Sep 15, 2014 at 15:37
  • I have edited my answer, however it is not complete but may be helpful. There is actually problem of broken html tag and may be that's why WordPress does not handle html tags in excerpt.
    – Domain
    Sep 15, 2014 at 16:03
  • Maybe you are looking for something like this
    – Tomás Cot
    Sep 15, 2014 at 16:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.