Keep HTML Tags in WordPress Limit Posts – the_content_limit

WordPress - the logoThis function, the_content_limit  controls the maximum amount of characters displayed for an entry on the main page on WordPress homepage posts, e.g Featured Posts, Recent Posts
However , the_content_limit stripped HTML tags just like the_excerpt. What if we want to keep HTML tags

We make modification to the function, the_content_limit which is usually found in functions.php


function the_content_limit($max_char, $more_link_text = '(more...)', $stripteaser = 0, $more_file = '') {
$content = get_the_content($more_link_text, $stripteaser, $more_file);
// remove  shortcode
$content = preg_replace("/\/", '', $content);
// short codes are applied

$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
$content = strip_tags($content,'
,<b>,<strong>,<a>,<i>,
');

if ((strlen($content)>$max_char) && ($espacio = strpos($content, " ", $max_char ))) {
$content = substr($content, 0, $espacio);
$content = $content;
echo "
";
echo $content;
echo "...";
echo "

";
}
else {
echo "
";
echo $content;
echo "

";
}
}

We remove $content = strip_tags($content);  from original code of the_content_limit and replace it with $content = strip_tags($content,'<p>,<b>,<strong>,<a>,<i>,<br>’);
This will allow the_content_limit to show paragraph, bold texts, italic texts.

What is strip_tags?

We can remove all html tags from the content by using strip_tags string function in PHP. This function can be used to collect only the content part without reading the html formatting of the page. Here is the syntax

strip_tags (input string [, string allowable_tags])

This function also allows one optional string where we can keep the tags which are not to be removed. Say we don’t want the hyper links to be removed. So we will allow the linking tag <a href to be kept as it is. Here is the syntax for this.

strip_tags($string_str, ‘<a>’);

In the above code $string_str is the input string, in our case it is $content

  • Pulia Zlaya

    may be so examples would be great