3

I am using the Metatag Module. Everything works as expected, till I checked the description for each node and saw that it is empty.

Since there is no output with [node:summary] I changed it to [node:body] which works, but now the whole node is in the description field... I checked the available tokens [*:summary, *:value, *:format] with no success.

Any suggestions how to use the [node:body] in a trimmed version?

  • If you add another field, like field_excerpt, can you use it with metatag? if so I might know a way for you. – Mołot Aug 29 '13 at 9:30
  • @Mołot well, that would work. But my customer does not want to fill in "additional" content/work. So I wanted to do it automatically with the existing node body content – wucherpfennig Aug 29 '13 at 9:40
  • Well, you don't always need to fill additional fields ;) I just needed to make sure you can use them at all. See my answer. – Mołot Aug 29 '13 at 9:59
3

You can use any field with Metatag, so simplest way would be to use Computed Field, that

lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields

In your custom php code for field computation, use code like this:

$body = $entity->body['und'][0]['value'];
$width = 160;
$body_trimmed = substr($body, 0, strpos(wordwrap($body, $width), "\n"));
$entity_field[0]['value'] = $body_trimmed;

It will truncate on the word boundary, giving you no more than $width characters. More about truncating on StackOverflow.

Then, simply feed this computed field to Metatag.

  • would you add (as for the computed field settings): $body = $entity->body['und'][0]['value']; $width = 160; $body_trimmed = substr($body, 0, strpos(wordwrap($body, $width), "\n")); $entity_field[0]['value'] =$body_trimmed; to make it complete? – wucherpfennig Aug 29 '13 at 10:40
  • 1
    @wucherpfennig code updated. Thanks :) And be sure to read SO question I linked, there are some useful hints how to trim safely. – Mołot Aug 29 '13 at 10:42
0

Thanks @Molot!

I was looking for a way to put a trimmed description field into another field called summary. You would think Drupal would do this automatically but the summary field is only populated if a user enters it manually.

My code looked like this:

$desc = $entity->field_prj_desc['und'][0]['value'];
$width = 140;
$desc_trimmed = substr($desc, 0, $width);
$entity_field[0]['value'] =  $desc_trimmed;

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.