When creating a node (e.g. Basic page) If you leave the summary textarea blank it uses a trimmed value of full text in the body textarea as the summary.

When using [node:summary] token as the default token for the meta description, it should pull a trimmed value from the body textarea.

Workarounds:
1. Once you fill in the summary, it does indeed create the meta description
2. changing the token to [node:body] for the meta description and flushing cache does create a meta description (although too long)
I guess what I am requesting is the ability to define [node:summary] in the default meta description for content and if nothing is in that field, it pulls a trimmed version of the body field.

This is a core bug. Interested people should help work on the patches in #1300920: The [node:summary] token does not output anything for body fields without a manual summary.

There is also a patch you can use for Drupal 7: http://drupal.org/node/1300920#comment-6779546

Files: 
CommentFileSizeAuthor
#79 metatag-n1295524-79.patch2.63 KBDamienMcKenna
PASSED: [[SimpleTest]]: [MySQL] 21 pass(es).
[ View ]
#78 metatag-n1295524-78.patch2.14 KBDamienMcKenna
PASSED: [[SimpleTest]]: [MySQL] 21 pass(es).
[ View ]
#74 node_summary_token.tar_.gz14.29 KBAlauddin
#20 [summary-tokens]-[1295524]-[19].patch8.27 KBnicoz
FAILED: [[SimpleTest]]: [MySQL] Unable to apply patch [summary-tokens]-[1295524]-[19].patch. This may be a -p0 (old style) patch, which is no longer supported by the testbots.
[ View ]
#1 2011-09-30_12-36-39.png167.13 KBhighrockmedia

Comments

StatusFileSize
new167.13 KB

I am having the same issue. Note that Drupal says "Leave blank to use trimmed value of full text as the summary." This implies that the token will work that way too. At the very least if this is not the case, I would not have "[node:summary]" as the default token as my users would never figure out that they have to manually put in a summery for this to work.

I'm having the same issue - subscribing.

subscribing... i have the same problem...

Filed an issue with core at #1300920: The [node:summary] token does not output anything for body fields without a manual summary. We may have to drop providing a default of [node:summary] for nodes unless we provides some support in Token module to fix this.

I am glad I found this I thought I was going batty. If someone has a snippet to pull the trimmed summary we could write a custom token.

Version:7.x-1.0-alpha2»

I have some code I'm working on in Token.module to provide [node:summary]. The question is what is the default string limit the token should use? Because the default for a summary is 600 characters.

Isn't there a variable to control the default summary length? Or was that removed in D7?

It's a per field instance setting now, and we can't always rely on it being available since the user could change what formatter is used on a body field.

Version:» 7.x-1.0-alpha2

if you use field_get_items wouldn't it take into account the language and formatter

I'm having the same issue - subscribing.

Subscribe.

@seezee. no need to place a comment to subscribe to a thread. Use the "follow" button at the top.

A (temperary) solution:

Make a view with the first 200 characters text, make a field with this view in your content type, place the field token in the Meta tag setup, hide the field with css:

Make a view named 'Meta tag description'
Make a block in that view with the fields
-- Node body:
----- Rewrite settings: max length 200 (or less) , Remove HTML tags, Remove whitespace
-- Filter: publiced and node type(s) you want
-- Contextual filter: NID: Provide default value type 'Content ID from URL'
Install module 'View reference'
For the content types you want to have a Meta description from the body vield:
Make a View reference field name 'Metatag description' fieldname 'field_metatag_description' with setup:
-- Views that can be referenced : 'Meta_tag_description blok '
-- Default value: 'Meta_tag_description blok'
Check the display of this field in your content type (s): Label: hidden, format: default view
In the Meta tag node settings page admin/config/search/metatags/config/node klick the [node:field_metatag_description] token (in Nodes tokens) in the description field.
Hide this field in css:
.view-meta-tag-description {
display: none;
}

This works for me, I had to patch viewreference because of a missing title error, the patch is here: Viewreference http://drupal.org/files/issues/1128444.patch
I first installed this with the viewfield module, but the field viewfield generates in the token is not clean text.
Remember that existing nodes need some manual adjustments (View Meta tag description block and Metatag description field)

subscribe!

a.luiz.n - please use the "follow" button at the top to "subscribe" to issues now.

dup- removed

I have solved it by introducing new alter hook in the metatag_field_attach_view_alter().

See the code below:

<?php
/**
* Implements hook_field_attach_view_alter().
*/
function metatag_field_attach_view_alter(&$output, $context) {
 
$entity_type = $context['entity_type'];
 
$entity = $context['entity'];
  list(
$entity_id, $revision_id, $bundle) = entity_extract_ids($entity_type, $entity);
  if (
metatag_entity_supports_metatags($entity_type, $bundle) && $context['view_mode'] == 'full' && _metatag_entity_is_page($entity_type, $context['entity'])) {
   
$cid = "output:{$entity_type}:{$entity_id}";
    if (
$cache = cache_get($cid, 'cache_metatag')) {
     
$output['metatags'] = $cache->data;
    }
    else {
     
$metatags = isset($entity->metatags) ? $entity->metatags : array();
     
$instance = "{$entity_type}:{$bundle}";
     
// Build options for meta tag rendering. The context variable already
      // contains entity type, entity, view mode, language, etc.
     
$options = $context;
     
// Ensure we actually pass a language object rather than language code.
     
$languages = language_list();
      if (isset(
$context['language']) && isset($languages[$context['language']])) {
       
$options['language'] = $languages[$context['language']];
      }
     
// Reload the entity object from cache as it may have been altered by Panels.
     
$token_type = token_get_entity_mapping('entity', $entity_type);
     
$entities = entity_load($entity_type, array($entity_id));
     
// Allow to alter the entity before it is set as token data.
     
drupal_alter('metatags_' . $entity_type . '_token_data', $entities[$entity_id]);
     
$options['token data'][$token_type] = $entities[$entity_id];
     
$options['entity'] = $entities[$entity_id];
     
// Render the metatags and save to the cache.
     
$output['metatags'] = metatag_metatags_view($instance, $metatags, $options);
     
cache_set($cid, $output['metatags'], 'cache_metatag');
    }
   
// We have to add a '#field_type' property otherwise
    // rdf_field_attach_view_alter() freaks out.
   
$output['metatags']['#field_type'] = NULL;
  }
}
/**
* Implements hook_metatags_node_token_data_alter().
* Alters node entity object to set summary to be used in token replacements.
* @param object $entity
*   In this case it is the node object.
*/
function metatag_metatags_node_token_data_alter(&$entity) {
 
$body_field_item = array_shift(field_get_items('node', $entity, 'body'));
 
$langcode = field_language('node', $entity, 'body');
  if (empty(
$body_field_item['summary'])) {
   
$entity->body[$langcode][0]['summary'] = text_summary($body_field_item['value'], NULL, 160);
  }
}
?>

Did you put this in your template.php? I tried that (renamed metatag_field_attach_view_alter to mytheme_metatag_field_attach_view_alter and metatag_metatags_node_token_data_alter to mytheme_metatag_metatags_node_token_data_alter), but saw no change.

Works like a charm blueminds

StatusFileSize
new8.27 KB
FAILED: [[SimpleTest]]: [MySQL] Unable to apply patch [summary-tokens]-[1295524]-[19].patch. This may be a -p0 (old style) patch, which is no longer supported by the testbots.
[ View ]

Rolled it into a patch.

@nicoz: I'm not so brave to try this patch. Completely remove the module's menu items is really the solution? Or I miss something?

Not into template.php. The metatag_field_attach_view_alter() should be replaced in metatag.module and metatag_metatags_node_token_data_alter() is a new function to be added into metatag.module

The rest of the metatag.module file stays unchanged.

Status:Active» Needs review

Status:Needs review» Needs work

The last submitted patch, [summary-tokens]-[1295524]-[19].patch, failed testing.

subscribing

@adamwhite, you can now simply use the Follow button at the top of an issue queue to subscribe to an issue, rather than filling the queue with a "subscribing" post.

@shonk I did not realize that. Cheers.

The core patch http://drupal.org/node/1300920#comment-5417072 works fine and fix this issue.

#17 worked like a charm. Thanks

#17 works for me!

Even with #17 on Metatag 7.x-1.0-alpha4 or Drupal core patch on Drupal 7.10, node:summary is still not displayed on all of my content types, only one works. I'm using Display Suite, and the one which is working is using Display Suite also ! After applying both patch I cleared my cache.

The only difference between these content types, is the overriding of default metatags with the inclusion of og:image on the one which is working.

Any idea ?

EDIT: I desactivated the metatags overriding, and the node:summary is still displayed. So it doesn't seem related.

by applying #17, when body is empty, I have the followin error:

Warning : array_shift() expects parameter 1 to be array, boolean given in metatag_metatags_node_token_data_alter() (ligne 455 dans /home/3u4u/domains/XXXX.com/prod/sites/all/modules/metatag/metatag.module).

After applying Drupal Core patch, [node:summary] token is correctly generated even if summary is not manually filled.
But Metatags description and og:description is still empty.(I applyed patch #17)

Even with manually body summary filled, the metatag is also empty...

I tried to manually set metatag description and also keywords in vertical tabs menu, and guess what ? It also doesn't work !

#17 workes for me. Thanks!

Any clean solution for this problem? I believe this is urgent.

Big thanks for blueminds for #17, works perfectly!

Hmm, I created a custom token [node:summary-or-trimmed:300] that takes the number that is put in last as the length of the trimmed body last night. If the summary is empty, it will trim the body and return that. Too bad I did not see this thread before...

@Marty: would you like to share the code? I've planned to developed a token like your but for custom fields :-)

Version:7.x-1.0-alpha5» 7.x-1.0-alpha2
Category:bug» feature
Priority:Critical» Normal

@FiNeX: sure. See below.

I'm not sure if everything I've done is the way it should be done, but it works for now. One thing that I'm uncertain of are if there is a better way to get the number of characters that the trimmed version of the body should be from dynamic part of the token (I'm now simply exploding the name of the token into an array).

Any improvement tips are welcome!

/**
* Implements hook_token_info().
* Based on example from drupal.org/node/1308488.
*/
function my_module_token_info() {
  $info['tokens']['node']['summary-or-trimmed'] = array(
    'name' => t('Summary or trimmed'),
    'description' => t('The summary or body of a node trimmed to the given number of characters.'),
    'dynamic' => TRUE,
  );
  return $info;
}
/**
* Implements hook_tokens().
* Based on example from drupal.org/node/1308488.
*/
function my_module_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  $sanitize = !empty($options['sanitize']);
  if ($type == 'node' && !empty($data['node'])) {
    $node = $data['node'];
    $body_field_items = field_get_items('node', $node, 'body');
    foreach ($tokens as $name => $original) {
      $trimmed_or_summary = '';
      $split_name = explode(':', $name);
      if ($split_name[0] == 'summary-or-trimmed') {
        if (isset($body_field_items[0]['summary']) && $body_field_items[0]['summary'] != '') {
          $trimmed_or_summary = $body_field_items[0]['summary'];
        }
        else {
          $teaser_length = 200;
          if (isset($split_name[1])) {
            $teaser_length = (int) $split_name[1];
          }
          $text = check_markup($body_field_items[0]["value"], $body_field_items[0]["format"]);
          // When a html closing tag is immediately followed by an openening tag, put a space in between.
          $text = preg_replace('/(<\/[^>]+?>)(<[^>\/][^>]*?>)/', '$1 $2', $text);
          $trimmed_or_summary = truncate_utf8(strip_tags($text), $teaser_length, TRUE, FALSE);
        }
        $replacements[$original] = $sanitize ? filter_xss($trimmed_or_summary) : $trimmed_or_summary;
      }
    }
  }
  return $replacements;
}

EDIT: removed the PHP syntax highlighting because that broke line 40...

EDIT: corrected wrong function name...

I created a module based on #39 above but had a few issues. There is a syntax error on line 40, should be: preg_replace('/. Beyond that I enabled the module, cleared my cache and input [node:summary-or-trimmed:300] into the metatag Description field in a node but got the error when saving: The Description is using the following invalid tokens: [node:summary-or-trimmed:300].. Not sure what else I might be doing wrong.

The bug in line 40 is created by the input filter on drupal.org, because in the source the '/ is there. Do you see the token in the token list when you enable your module?

@Marty2081 - No I do not see the token when I enable the module. I am not sure what else I might be doing wrong. Thanks.

After testing the Meta Description (manually filled or in use with tokens), i can say it's not working at all.

** edit

Edit the 'description' field and click 'Save' (for example a test sentence: this is the meta description). Then reopen the saved content and look at the 'description' field. It says [node:summary] again. When visiting the page, opening the source, there is no meta description at all.

Version:7.x-1.0-alpha2» 7.x-1.0-alpha5
Category:feature» bug
Priority:Normal» Critical

That's odd, it's working for me on several sites.

Have you tried the core patch in #28?

@Jeordy are you using Display suite? because that sounds just like this issue http://drupal.org/node/1286148

No, i've installed the Metatag module on several sites, but none of them are showing the meta description in the source of the page.

The weird thing is, the description field just keeps turning back to [node:summary], even after pasting some text and saving the node. I've tested it on 5 sites, all with the same problem.

Jeordy, that is actually two separate issues that are unrelated. Had me confused for a while too. :)

Run the dev version of the module and that will solve the non-saving issue when editing nodes. Alpha 5 has a problem with displaying saved fields. The changes are saved but not displayed.

The Description meta tag not appearing is an issue with Drupal. See either #39 above or #28. Personally I like #39 because it leaves the core alone.

The error in @Marty2081 #39 code is in line 5...

<?php
function my_module_base_token_info() {
?>

should be

<?php
function my_module_token_info() {
?>

There shouldn't be the word _base in the function. :)

Version:7.x-1.0-alpha2» 7.x-1.0-alpha5
Category:feature» bug
Priority:Normal» Critical

@Das123: you're right. My module was named "gm_ base" so I forgot to take out "_base". I've updated the snippet above.

@Marty2081, thanks for the helper module... I've added it to a site today and it works like a charm! Hopefully the next snapshot of Metatag won't need it but for now, that is a solid solution and leaves the module un-hacked.

Cheers,
Andrew

@awasson: nice to know that it helped you. I don't know if this is a Metatag issue or a core / Token module issue since I would expect the token [node:summary] to work like my solution.

@blueminds - Thanks for your solution on this issue. I am attempting to implement and am not getting positive results.

http://falcon.friendswoodtech.com/node/4

I made the change in metatag.module, but still not rendering description if summary left blank. Not sure what I may have done wrong. Any clues???

Thnx guys/girls!!

Works great now!

Excellent, works a charm! ... unless there is a line break in the body - HTML or plain text format, in which case only the first line is shown even if that is less than the number of characters specified in the token variable value.

Many thanks for your work on this guys :)

on multilingual site just patch below codes on line 464 of metatag.module:

$entities = entity_load($entity_type, array($entity_id));
+ if (empty($entities[$entity_id]->body[$options['language']][0]['summary'])) {
+ $entities[$entity_id]->body[$options['language']][0]['summary'] =  text_summary($entities[$entity_id]->body[$options['language']][0]['value'], NULL, 160);
+ }

Using Metatag 7.x-1.0-alpha6 and patch from http://drupal.org/node/1300920#comment-6200094 gets the [node:summary] output and properly populated fields.

#39 is working great for me - thanks :)

I took this route because the core patch mentioned in #57 still looks like a work in progress (and technically is for D8 I think).

Version:7.x-1.0-alpha5» 7.x-1.x-dev
Status:Needs work» Postponed

This is completely dependent upon the core issue #1300920: The [node:summary] token does not output anything for body fields without a manual summary, if you need this functionality please use the patches from there and help reviewing that issue. For now I'm marking this as postponed.

Just wanted to say that the solution from #39 worked perfectly for me. I also chose this route because, like pushka mentioned, this patch seems to be under active development.

As this is still open after a year, and I did a review of a recent site and found the issue was killing our rich snippets and open graph work we'd taken such care to put in, I've released a tiny fix-up module for anyone who needs it fixed NOW and doesn't want to hack core.
Node Summary Token

This is an interim fix for a core+metatag issue, and is intended to have a short lifetime. It's provided as a stand-alone module so that it can be applied to critical live sites without core hacks or -dev branches.
ONLY use this module if you are using metatag and want the "description" to use your nodes body teaser text (which is the expected default) and you've found that it's not working.

This is a work-around mini-module that addresses the long-standing problem identified in Sept 2011 as "[node:summary] does not work in default content meta tag when summary left empty" and eventually branched as a core patch in "The [node:summary] token does not output anything for body fields without a manual summary" - which got bumped to Drupal 8 (no backport yet) and at October 10, 2012, is still not in.

The code here is based on a stand-alone module example from Marty2081 on April 18, 2012 (and the code that is pending inclusion in D8) but I reworked it to use hook_tokens_alter so that it could override the core [node:summary] token transparently instead of using a new made-up replacement token.

@ DamienMcKenna re bumping #1300920
- that's gone off onto D8-land, so it's a while away from being a usable fix for a stable D7 site released today... but I really don't know what's slowing it down. I see/understand no blockers in that queue.
I can +1 the importance there (will do) but it just looks a bit bogged down to me, coming in at this point.

@dman: thanks.

Now that at least part of that issue's problems have been shuffled off to another issue, the current patch can be tweaked accordingly and re-submitted. Hopefully we'll get this taken care of by the next stable release of Drupal.

#62 module works for me.

#62 works for me, too. Thanks!

Just wanted to thank dman for the mini-module described in #62. It works like a charm!

Huge thanks to @dman for providing #62, indeed!
Does this issue belong to meta tag? I guess it's node_tokens() problem (summary field arrives empty), and should be handled in core.

@valthebald: The question comes up often enough that it's worth tracking the discussion here while #1300920: The [node:summary] token does not output anything for body fields without a manual summary is being worked on.

@DamienMcKenna: great, thanks for the link

I applied the patch in #39. Thank you to @Marty2081 for doing the heavy lifting on this. I just want to point out that this, defining your own override in a custom module, is the best way of solving this problem for a couple of reasons:

  1. You aren't hacking the MetaTags module. Yes, "hacking." You would be hacking because the maintainer has stated the problem is with Drupal core and will never be addressed here. Once Drupal core is fixed, your hacking code is now redundant and in the way of core functionality.
  2. You have more control over how the token is built. I took the code in #39 and expanded it to handle terms. You'll also notice I changed the field name as I am not using the default "body" field and that I only use that field if the "field_abstract" is not defined on the node.

Below is the code as I implemented it in my "Swiss Army Knife" module called "base."

/**
* Implements hook_token_info().
* Based on example from drupal.org/node/1308488.
*/
function base_token_info() {
  $info['tokens']['node']['summary-or-trimmed'] = array(
    'name' => t('Summary or trimmed'),
    'description' => t('The summary or body of a node trimmed to the given number of characters.'),
    'dynamic' => TRUE,
  );
  $info['tokens']['term']['summary-or-trimmed'] = array(
    'name' => t('Summary or trimmed'),
    'description' => t('The summary or body of a term trimmed to the given number of characters.'),
    'dynamic' => TRUE,
  );
  return $info;
}
/**
* Implements hook_tokens().
* Based on example from drupal.org/node/1308488.
*/
function base_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  $sanitize = !empty($options['sanitize']);
  $parse = FALSE;
  if ($type == 'term' && !empty($data['term'])) {
    $parse = TRUE;
    $term = $data['term'];
    // Get content.  Try for abstract first.
    $body_field_items = field_get_items('taxonomy_term', $term, 'field_abstract');
    if (!isset($body_field_items[0]['value']) || ($body_field_items[0]['value'] == '')) {
      $body_field_items = field_get_items('taxonomy_term', $term, 'field_body');
    }
  }
  else if ($type == 'node' && !empty($data['node'])) {
    $parse = TRUE;
    $node = $data['node'];
    // Get content.  Try for abstract first.
    $body_field_items = field_get_items('node', $node, 'field_abstract');
    if (!isset($body_field_items[0]['value']) || ($body_field_items[0]['value'] == '')) {
      $body_field_items = field_get_items('node', $node, 'field_body');
    }
  }
  if ($parse) {
    foreach ($tokens as $name => $original) {
      $trimmed_or_summary = '';
      $split_name = explode(':', $name);
      if ($split_name[0] == 'summary-or-trimmed') {
        if (isset($body_field_items[0]['summary']) && $body_field_items[0]['summary'] != '') {
          $trimmed_or_summary = $body_field_items[0]['summary'];
        }
        else {
          $teaser_length = 300;
          if (isset($split_name[1])) {
            $teaser_length = (int) $split_name[1];
          }
          $text = check_markup($body_field_items[0]["value"], $body_field_items[0]["format"]);
          // When a html closing tag is immediately followed by an openening tag, put a space in between.
          $text = preg_replace('/(<\/[^>]+?>)(<[^>\/][^>]*?>)/', '$1 $2', $text);
          $trimmed_or_summary = truncate_utf8(strip_tags($text), $teaser_length, TRUE, FALSE);
        }
        $replacements[$original] = $sanitize ? filter_xss($trimmed_or_summary) : $trimmed_or_summary;
      }
    }
  }
  return $replacements;
}

Thanks for this code capellic!

Just a heads up if you are using this code: your field names might vary from the code above. Double check field_get_items($entity_type, $entity, $field_name) in the code above for your site setup. If you are using the default body field provided by node, it will be field_get_items('node', $node, 'body') not field_get_items('node', $node, 'field_body')

Priority:Critical» Normal

Reducing this to a Normal issue as it's a bug in Drupal core.

Using posts #70 and #71 worked for me.
Thank you !

StatusFileSize
new14.29 KB

#62 worked like a charm.
thank you @dman

For those who dont use git or not familiar with git, I am attaching the module here.

hope that helps

Sorry I didn't think to push this to a public project. I was hoping it wouldn't remain needed for long.
But I might as well bump it up to be easier to download.
Good idea to post this as an upload here Alauddin.
I've also bumped the project status so a download will become available there ... http://drupal.org/node/1911432

using [node:summary] with Meta tags 7.x-1.0-beta1, works correctly for me.

7.x-1.0-beta4 doesn't work for me.

#62 and #74 works – thank you!

Another approach:
http://drupal.org/project/fixcore (Display issues -> Empty summary token) works, for me, too.

Status:Postponed» Needs review
StatusFileSize
new2.14 KB
PASSED: [[SimpleTest]]: [MySQL] 21 pass(es).
[ View ]

How about we not wait any further and provide a band-aid that can be removed once the core fix is committed?

StatusFileSize
new2.63 KB
PASSED: [[SimpleTest]]: [MySQL] 21 pass(es).
[ View ]

A working patch.

Status:Needs review» Fixed

I've committed the patch from #80, so the next release will have a working [node:summary] token. *happydance*

hey @DamienMcKenna I'm joining you in the *happydance*! This issue has been driving me mad for about six months and I never quite got my head around it, because there are so many parts to it, at least in my mind. There is meta tag, og:tag, body summary, body trimmed, and meta tag module vs other solutions. I never pinpointed the problem in my haste to get things done and was forced to hack around in the projects I was working with.
But now with the current dev version (April 5) it just works out of the box. Just like I would wish in my dreams. Ergo: dreams can come true!
Let me buy you a beer or a beet juice in Portland!

@leanderl: I'm glad it's working well for you. I won't be at Drupalcon Portland this year, but I appreciate the sentiment :)

I was just looking for this! thanks.

Patch has added a file to my Drupal install, but still doesn't work. Is there anything else I have to do?

@ebpo: Clear your caches?

@DamienMcKenna : i made an account just for that. I feel ridiculous.

@ebpo: Welcome to drupal.org, we hope your stay will be comfortable :-)

Status:Fixed» Closed (fixed)

1.0-beta6 is out, so I'm closing this issue in the interest of keeping the issue queue clean.

Issue summary:View changes

x