0

I am using a custom function to truncate text based on an argument which states the number of allowed characters. Here is my code:

function bm_best_excerpt($length, $ellipsis, $content) {
$text = $content;
$text = strip_tags($text);
$text = substr($text, 0, $length);
$text = substr($text, 0, strripos($text, " "));
$text = $text.$ellipsis;
return $text;
}

ON any page, I can truncate text by grabbing a Wordpress custom field (which contains a string of text) and running it through this function like so:

<?php $excerpt = get_field('long_description'); ?>
<p><?php echo bm_best_excerpt(70, ' ... ', $excerpt); ?></p>

This works great, and displays the first 70 characters of $excerpt. I want to modify this function, so it first counts the number of characters in a title (above the description) and then uses any leftover characters for this description.

To illustrate this, lets say I want to allow for 80 characters total. My RAW HTML is below:

Here is a Title that is fairly long

Here is a description followed by some Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

I want the TOTAL amount of characters between the title and description to be 80. The title has 35 characters, which leaves 45 characters left for the description.

How would I modify the above function to allow for the counting of an additional content variable (as an argument) and then the subtraction against the $length? I would want the function to look something like this:

function bm_best_excerpt($length, $ellipsis, $content1, $content2) {

Where $content1 is the title and $content2 is the description

JCHASE11
  • 3,901
  • 19
  • 69
  • 132
  • function bm_best_excerpt($length, $ellipsis, $content, $content2='') { $text=$content.' '.$content2; ? – Waygood Aug 14 '12 at 16:19
  • not sure I understand what you are trying to convey – JCHASE11 Aug 14 '12 at 16:22
  • You just need to add the content onto the end of the title (separated by a space for readability) and truncate the lot to 80. – Waygood Aug 14 '12 at 16:27
  • related: You should try and see if you can use the mysql function LEFT() to only fetch a limited number of chars from your db in the first place ... – Cups Aug 14 '12 at 16:28

1 Answers1

0

Try this to add the strings together and process as one:

function bm_best_excerpt($length, $ellipsis, $content, $content2='') {
    // default content2 to empty string, allowing use of old method to still be valid
    $text = $content.' '.$content2; // add the second content to the end of the first
Waygood
  • 2,657
  • 2
  • 15
  • 16