1

I'd like to print (in Views - custom/PHP field) random part of body of a node, as a kind of teaser, different with every print.

Any ideas? Thanks! :]

Szy.

1 Answer 1

2

here you go: :)

$length = 50;

// strip html tags from body
$body = strip_tags($data->body);

// check that the body's actually longer than your snippet length
if (strlen($body) <= $length) {
  return $body;
}
else {

  // find a random starting point between the beginning and 50 chars from the end
  $max = strlen($body) - $length;
  $start = rand(0, $max);

  // set ellipsis variables
  $prefix = $start ? '...' : '';
  $suffix = ($start == $max) ? '' : '...';

  return $prefix . substr($body, $start, $length) . $suffix;
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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