I found many issues for "addind metatags for page display of views". But didn't found any for: displaying metatags as fields in Views.

I have administration view (table):
VBO-content | Nid | Title | Author | Published | Created | edit link

How to add there some Metatag as column?
I need display it and filter by it to easily find non-tagged nodes.

Or am i blind? Spent about 2 hours of trying.


Edit: A sandbox implementation can be found here: metatag_views_field.
Support from Acquia helps fund testing for Drupal Acquia logo

Comments

kmajzlik’s picture

Ok, now i found it as mostly impossible.
Hm, storing metatgs as serialized array is maybe good for performance, but a hell for working with that programatically and SQL...

I will let it open if someone has some proposal.

kmajzlik’s picture

FileSize
1.12 KB

First workaround attached.
Only thing it does is showing full serialized data as string, filter as normal views string.
Works only with nodes at this time.

I expect i will create more views handlers in future with unserialize data and also more entity_types support (at least taxonomy_term).

Dave Reid’s picture

Are you trying to do something like the following? I'm not exactly sure how we could support filtering on serialized data.

kmajzlik’s picture

Yes i am trying something like this. At the moment great result for me is: have metatags / dont have metatags.

I used this PHP field:

if(strlen($row->data)) {
  $arr = unserialize($row->data);
}
if(is_array($arr)) {
  foreach($arr as $delta => $tag) {
    if($delta == 'robots') {
     print '<strong>' . $delta . '</strong>:<br />';
     //dpm($tag);
     foreach($tag['value'] as $d => $t) {
       print '- ' . $d . ': ' . $t . '<br />';
     }
    } else {
      print '<strong>' . $delta . '</strong>: ' . $tag['value'] . '<br />';
    }
  }
}

Not ideal but better than nothing.

We are finishing website and 2 people working on metatags - i dont have any other idea how to help them with searching content without tags.

DamienMcKenna’s picture

Title: Views support » Expose meta tag data as a Views field

Clarified the title.

xurizaemon’s picture

I ran into this just now and thought I'd share an easy workaround using computed_field. We wanted to filter by (not display) metatag keywords in a Views search, so that people can type "schools" and see a result for "Education", and staff don't have to double-handle keywords.

  • On the content type, add a computed_field field named 'field_keywords' with text storage
  • On the content type, set display of the field to off (I only want it to produce results in search, don't do this if you want to display metatag values)
  • On the view, add display fields for the fields you want to filter against (title, body, keywords for me), setting Exclude from display
  • Also on the view, add a combine fields filter for the fields you want to filter by
  • Function to store the field is defined in custom module - see below
/**
 * Compute value for field_keywords, so we can use the result as a
 * filter result in views.
 *
 * Metatag module stores as serialized data, which makes keyword
 * filtering hard. Ref d.o #1906578.
 */
function computed_field_field_keywords_compute(&$entity_field, $entity_type, $entity, $field, $instance, $langcode, $items) {
  if (isset($entity->metatags['keywords']['value'])) {
    // split comma,separated,words to plain words (maybe redundant?)
    $entity_field[0]['value'] = str_replace(',', ' ', $entity->metatags['keywords']['value']);
  }
  else {
    $entity_field[0]['value'] = NULL;
  }
}

EDIT: Code updated to include else block, otherwise your computed result won't clear if you zap the stored metatags for a node.

Because I wanted this specific filter result, I didn't check until after doing this if Metatag implemented hook_node_search_result() to produce keyword match results. Looks like it doesn't (#1368298: Index metatags for core search at time of writing).

You could easily build on the above to obtain displayable Metatag results. Sure, you're duplicating data in the DB, but consider it a cached display or search query table and that shouldn't keep you awake.

I've only tested this for about five minutes, I'll let you know if it's a wreck :)

Note that if the keywords value in your Metatags fields is empty, nothing will be stored - I expect this solution will only display *custom* keywords per-node, not site-wide keywords.

Paradoxetion’s picture

For someone who will face same problem (show metatags as field, like title or nid)

1) Install & Enable Views PHP module
2) Go to your view and add Node Id as field
3) Add field Global -> PHP code
4) Add this as output code

For keywords:

$result=node_load($row->nid);
$metkey = $result->metatags['und']['keywords']['value'];
print ( $metkey);

For description

$result=node_load($row->nid);
$metkey = $result->metatags['und']['description']['value'];
print ( $metkey);

And that's it! Hope it will help you to spend 2-3 hours of your life better ;)

kmajzlik’s picture

there should not be:

['und']

but

[LANGUAGE_NONE]

and yes, you are totally killing performance by using node_load() on all rows.

Paradoxetion’s picture

karlos007 ,

yes, you're right.
Better idea?

mgerbault’s picture

Title: Expose meta tag data as a Views field » Expose meta tag data as a Views field [SOLVED]
FileSize
2.4 KB

Thanks a lot, I have developped a little module inspired by #2.

See attached file

Mat

DamienMcKenna’s picture

@mgerbault: That's an excellent start, thank you! Would you mind if we take what you wrote and expand upon it with the goal of adding it to the main Metatag module?

mgerbault’s picture

@DamienMcKenna , yes if you want.
I need my module for a site where I use Metatag module ans sub-modules.

I suppose you can add meta keyword ...

Thanks

cameron prince’s picture

I don't know that I would call this one solved. In my testing, the module from number 10 did not work for views displaying taxonomy terms. It seems to be specifically for nodes.

ciss’s picture

Title: Expose meta tag data as a Views field [SOLVED] » Expose meta tag data as a Views field (sandbox)
Issue summary: View changes

@cameronbprince: The initial request was to provide integration for nodes - in that regard the solution in #10 will probably work.

But I think we can all agree that we should aim for a full integration. I started a new sandbox and claimed the name "metatag_views_field" since mgerbault didn't create a sandbox of his own.
The basic idea is outlined in the description. I've also created issues for each 1.0 step to help in planning. I haven't looked much under metatag's hood yet, so any input on the provided issues is appreciated.

Version 1.0 (and probably also 1.1) are requirements for a current project, so expect results in the next 2-3 weeks.

DamienMcKenna’s picture

Component: Code » Views integration
pixelz.gmd’s picture

#7 helped me a lot! thanks for that Paradoxetion!

To fix all the error codes gotten, I implemented an isset() check:

	$result=node_load($row->nid);
	$keywordsSet = isset($result->metatags['und']['keywords']['value']);
	if ($keywordsSet) {
		$metkey = $result->metatags['und']['keywords']['value'];
		print ( $metkey);
	} 

Hope this helps others! Still would be cool to use the module described here though!

dillix’s picture

Will this submodule be a part of metatags?

DamienMcKenna’s picture

Status: Active » Needs work

@dillix: Potentially. First off, it needs to be rolled as a patch.

ciss’s picture

Issue summary: View changes

@dillix, @DamienMcKenna: I'd like to keep metatag_views_field a separate project until it gets a green light for the 1.0 milestone. Otherwise we'll have to cope with large patches and lots of interdiffs.

The main problem left (for which I haven't created an issue yet) is multiple languages: hook_views_data joins don't allow to define joins on multiple fields, which is why I initially forced LANGUAGE_NEUTRAL. The best approach would probably be to use the field language selected for the view (views_handler_field_field is not the easiest handler around though - might be difficult to identify and port the relevant parts).

As for filtering and sorting: I'd strongly recommend to postpone those features, as I don't see a way yet to implement them without maintaining an additional index table for all metatag values.

drupalerocant’s picture

Hello,

I need this module you are doing for a project in which I need to create taxonomy terms with the metatags already filled in the articles.
I think this is the best way.
First with views I get the metatags and I can export them with views_data_export in a csv file and then import it with feeds.
The problem is that when using your module in the sandbox I get a WSOD (blank page).
Do you know Why is is happening?
Are you planning to create a usable release? It would be much appreciated.
Thanks in advance!

ciss’s picture

drupalerocant’s picture

Thank you very much, ciss, after following the issue you pointied me, I used the module in this issue and was able to show the metatag description in views. After that I changed in the module description for keywords and was able to show the keywords in views.
Problem solved!

dillix’s picture

@ciss, how to use your submodule with different language?

ciss’s picture

@dillix: Not yet implemented, as far as I recall. You'd need to patch the handler to respect the field language set for the view.

Edit: Patches welcome. :)

vimokkhadipa’s picture

Thank all but I installed the module metatag_views_field (# 10) but does not work for views of taxonomy.

andyg5000’s picture

Title: Expose meta tag data as a Views field (sandbox) » Add views field support for metatag
Status: Needs work » Needs review
FileSize
4.24 KB

Here's a patch that provides the metatag_views_field submodule to exposed metatag values to views fields!

DamienMcKenna’s picture

Title: Add views field support for metatag » Expose meta tag data as a Views field
DamienMcKenna’s picture

Thanks andyg5000!

dillix’s picture

Great news! I'm waiting for commit;)

Anonymous’s picture

I installed #10's module and then applied #26's patch. After setting up the view, everything seemed to work nicely except for the following error:

Notice: Undefined index: description in views_handler_field_node_metatag->render() (line 41 of /Users/jelepo/Documents/mydrupalsite/sites/all/modules/metatag_views_field/views_handler_field_node_metatag.inc).

I resolved the error by using isset() to check if the index exists before accessing it (read on stackoverflow). Just update line 41 to:

$rendered_value = isset($data[$this->options['data_key']]['value']) ? $data[$this->options['data_key']]['value'] : '';

andyg5000’s picture

Hey @jpoeng,

You should only be applying the patch in #26, not using the zip file module in #10. It sounds like the notice you're reporting is from the #10 module and that the patch was never applied. Can you try to reconfigure everything with just the current -dev of this module + #26 patch and report back?

Anonymous’s picture

Issue tags: +Ah thanks

@andyg5000: Thanks for the clarification. I applied #21's patch to the module and it's working now.

ChaseOnTheWeb’s picture

Issue tags: -Ah thanks
AlfTheCat’s picture

#26 works great for me.
It would be a great addition if metatag data would be available to views filters too. That way it's possible to filter results based on missing meta tags, meta descriptions that are too long, titles too short, etc.

DamienMcKenna’s picture

Status: Needs review » Needs work

Could this be expanded to cover other entity types too, e.g. terms, users, etc? Shouldn't it just be a case of adding more items to the $data['metatag']['table']['join'] array in metatag_views_field_views_data()?

ericwenger’s picture

Does this patch still work on the current dev/release? I tried both dev and release, and while I can add the fields in my view, there is no content showing. I do have manually entered page titles and descriptions so it shouldn't be a token related problem.

Views fields would really be convenient, but as an alternative is there any other way to export/import/work with meta titles and descriptions until this feature is finished?

DamienMcKenna’s picture

@ericwenger: That'll be tricky to do as the final meta tags aren't actually generated until the entity is rendered, the values aren't started in a table somewhere.

ericwenger’s picture

So...basically the only way to edit meta tags are via the node edit forms? Even with hundreds of nodes?

I have used Feeds to import lots of meta tags (which is great), and if I could find a way to export the meta tags back out, then the SEO guys could rework as they wish and I could re-import. But some meta tags have been edited via the node edit forms already so I need to do an export vs using my previous data import files...so how can I get that info back out without visiting each individual node?

The view field would fit the bill since I would simply create a view(s) to collect my data from. Just wanted to be clear that I'm not trying to hijack this thread for another purpose...I did come looking for the views field. ;-) But we can move this conversation somewhere else if you feel it should be.

Thanks Damien!

DamienMcKenna’s picture

@ericwenger: This Views integration was never intended to be for editing records, it's purely for reporting/exporting purposes.

If you need to do bulk editing of meta tags it might be easier to add text fields to the content type, use tokens to control what's output as the different tags, and then use existing solutions to import/export the field data.

ericwenger’s picture

FileSize
155.13 KB

Yes, I understand that. What I was trying to say is after adding the patch in #26, I'm now trying to create a view to show my meta data. I can add the meta title and meta description fields to the view (that part works as expected), but those fields in every row (node) in the view is blank. Does that make sense? Screen shots attached.

DamienMcKenna’s picture

Issue tags: +Needs tests

Ok, I follow, thanks for the clarification.

I guess this needs tests to make sure the functionality works as intended.

nikita_tt’s picture

Added some fixes to #26. This should fix #40

DamienMcKenna’s picture

Status: Needs work » Needs review

Thanks @nsk_ua. Lets see what the testbot says about it.

philsward’s picture

Trying to use this with a commerce catalog, and receiving the error:

Notice: Undefined index: value in views_join->build_join() (line 1576 of /home/user/public_html/sites/all/modules/views/includes/handlers.inc).

When adding to the "Parent Terms" view, I received the error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'metatag.entity_type' in 'on clause'

I'm guessing things haven't been setup yet for taxonomy terms?

The idea, is to use the view to output the catalog term metatag values from the field, as entered on the term page. The plan was to exclude the field, then use them with the (newly added) #2143979: Allow Views meta tags to "Use replacement tokens from the first row" to output the terms meta description for the requested page.

I'll note that I like the setup of the field. Very straight forward.

prathibha.sn’s picture

@ciss : https://www.drupal.org/sandbox/ciss/2228751 - This was very helpful for me to add meta title & meta description as fields for RSS feed view! Many thanks

castelar’s picture

The patch in #42 is working for fields. Thank you. As op said, I need to be able to filter by metatag also. Can't do that as far as I can tell. Is there a way to at least sort a table by metatag field?

DamienMcKenna’s picture

I've rolled the last patch into the main module and cleaned up the descriptions a little bit to be more clear what it does.

DamienMcKenna’s picture

strip_tags() the label.

philsward’s picture

@DamienMcKenna what would it take to expose the new metatag field to relationships? I'd like to be able to pull the metadata info in from a taxonomy field relationship but can't currently expose the metatag field to the relationship :-/

sillo’s picture

Rolled into the main module? - What main module? Metatag?
I am using 1.25 and i don't have any of these fields available in Views.

tcfunk’s picture

Any idea how to go about this in D8?

AlfTheCat’s picture

@sillo, have you tried the latest dev?

lukas.fischer’s picture

#51 +1 – Any idea how to go about this in D8?

Chris Matthews’s picture

DamienMcKenna's last patch in #48 still applies cleanly to the latest 7.x-1.x-dev and would be awesome to be included in the #2958474: Plan for Metatag 7.x-1.26.

rocasey’s picture

Applied patch in #48 and its exposing to views fields, great stuff! However am looking for filter implementation too like @castelar (#46). Any idea how to go about filtering by metatag?

DamienMcKenna’s picture

Status: Needs review » Needs work

A filter would have to be added as a separate option.

I think this could also be expanded to cover other entity types.

ciss’s picture

I think this could also be expanded to cover other entity types.

@DamienMcKenna For what it's worth, the metatag_views_field sandbox already implements generic entity support. If my remark in #19 is the only thing preventing the sandbox from being used as basis, I'd happily welcome its integration into metatag.

Any idea how to go about filtering by metatag?

@rocasey Not really possible with Views alone. Because the data is serialized you'd either have to create a separate search index of all values or rely on very fragile and slow regexp queries.

DamienMcKenna’s picture

This includes the full sandbox moved over as a patch for the main module.

DamienMcKenna’s picture

Status: Needs work » Needs review
ciss’s picture

Status: Needs review » Needs work
  1. +++ b/metatag.views.inc
    @@ -0,0 +1,85 @@
    +  // @todo Is it really a good idea to limit the entity types to those with
    +  // enabled Metatag defaults?
    

    Should get resolved and removed.

  2. +++ b/metatag.views.inc
    @@ -0,0 +1,85 @@
    +      'extra' => array(
    +        array('field' => 'entity_type', 'value' => $entity_type),
    +        // @todo Replace with real language support
    +        # array('field' => 'language', 'value' => LANGUAGE_NONE)
    +      ),
    

    I don't recall wether the current implementation matches the field integration in Views. I think matching behavior is a minimum requirement before this gets in. Ideally the only thing left here would be to remove the comment.

  3. +++ b/metatag.views.inc
    @@ -0,0 +1,85 @@
    +      // Name already in use, append a suffix and increase count.
    +      $safe_name .= '_' . $blacklist[$safe_name]++;
    

    This is a bit hard to read. Increment and assignment should be performed separately. Alternatively the order of operations in the comment needs to match (inc, then assign).

  4. +++ b/views/metatag_handler_field_entity.inc
    @@ -0,0 +1,101 @@
    +    // The alias needs to be unique, so we use both the field table and the
    +    // entity type.
    +    // @todo Probably not necessary for this use case?
    +    $entity_type_alias = $this->table_alias . '_' . $entity_type . '_entity_type';
    +    $this->entity_type_alias = $this->query->add_field(NULL, "'$entity_type'", $entity_type_alias);
    

    Should get resolved and removed.

  5. +++ b/views/metatag_handler_field_serialized_list.inc
    @@ -0,0 +1,21 @@
    +class metatag_handler_field_serialized_list extends metatag_handler_field_serialized {
    

    Needs another pair of eyes. As far as I recall we never actually had any list tags in our projects.

DamienMcKenna’s picture

Title: Expose meta tag data as a Views field » Expose meta tag data as a Views field (D7)
philsward’s picture

#58 causes the error:

The handler for this item is broken or missing and cannot be used. If a module provided the handler and was disabled, re-enabling the module may restore it. Otherwise, you should probably delete this item.

#48 still appears to work for the most part, outside of the error on the actual views output page (not the view admin page):

Notice: Undefined index: value in views_join->build_join() (line 1688 of /home/user/public_html/sites/all/modules/contrib/views/includes/handlers.inc).
ciss’s picture

@philsward #58 is an entirely different implementation based on Metatag Views Field. Because handler names and configuration masks have changed you will have to manually add back the corresponding fields to your views (and remove the old ones).

philsward’s picture

@ciss >> #58 is an entirely different implementation based on Metatag Views Field.

I figured that part out.

The error came when adding the field itself. Just adding that field caused the error on a fresh install with the patch. Did I miss something?

ciss’s picture

Did I miss something?

Nope, the patch is missing something: The files[] entries for the handlers. Add these lines in metatag.info and clear the cache:

files[] = views/metatag_handler_field_entity.inc
files[] = views/metatag_handler_field_serialized.inc
files[] = views/metatag_handler_field_serialized_list.inc
philsward’s picture

@ciss Beautiful! That did it!

Especially love: Use default metatag value Great job on paying attention to detail :D That was exactly what I needed to check against 300+ pages.

Leo Pitt’s picture

Updated patch at #58 to include files[] entries as per #66.

perke’s picture

I'm trying to figure out the correct way to get this functionality. From what I see, I should be using 7.x-1.x-dev and only the patch from #68.

Would that be correct?

butterkitty’s picture

@perke I used the patch from #68 on my 7 install and it works very well from my testing. I don't feel like it warrants the "Needs Work" status anymore.

ciss’s picture

I don't feel like it warrants the "Needs Work" status anymore.

@butterkitty A good method to find open tasks in an issue is to look for the comment that changed the status to "Needs work". In this case it will lead you to #60 in which I outlined a few points that need to be taken care of. :)

fbreckx’s picture

Tested patch #68. I can select the fields in views, but then it says 'Broken/Missing handler' when added.

perke’s picture

@fbreckx yeah, it seems that patch creates files in the module's root directory instead of the /views directory. Until the patch is fixed, you can just create views dir and move the new files there. See #66 for the files list.

fbreckx’s picture

@perke Great, that does the trick. Thank you!

ciss’s picture

@perke @fbreckx I don't see how the patch would do that. How did you apply it, and from what directory?

To apply the patch:

  1. change into the metatag module directory
  2. download the patch via
    wget https://www.drupal.org/files/issues/2019-08-20/expose-meta-tag-data-as-a-views-field-1906578-68.patch
  3. If the metatag directory is not a git clone of metatag:
    1. Make sure you have the latest code version from the repository, and no prior patches applied.
    2. Verify that the patch can be applied cleanly:

      patch -p1 --dry-run < expose-meta-tag-data-as-a-views-field-1906578-68.patch
    3. Apply the patch:

      patch -p1 < expose-meta-tag-data-as-a-views-field-1906578-68.patch
  4. Otherwise:
    1. Make sure your working directory is clean by running git status
    2. Verify that the patch can be applied cleanly:

      git apply --check expose-meta-tag-data-as-a-views-field-1906578-68.patch
    3. Apply the patch:

      git apply expose-meta-tag-data-as-a-views-field-1906578-68.patch
philsward’s picture

Fix:

With 1.27, I get 1 hunk failed for metatag.info.

Looks like it's pointing to line 102, but should be pointing at line 96 if I'm not mistaken? Looks like a small re-roll on #68 needs to be done to account for recent changes.

Add:

1) Looks like the "Filter Criteria" isn't pulling in which doesn't allow any filtering on the metatag info.
2) Similar to the filter criteria, the metatag info isn't exposed to sorting either.

arpas’s picture

vchen’s picture

#77 worked for me. I was able to add an Advanced Meta tage field and drill it down to Robots.

I see that sorting and filtering is another can of worms; that's unfortunate. However, I'm happy that at least I can see which nodes have a certain meta tag.

lunk rat’s picture

Status: Needs work » Reviewed & tested by the community

#77 applied cleanly to 7.x-1.27 and is working fine. Just having the ability to display metatag fields in views is a significant enhancement. Works well for providing content editors with a broad at-a-glance overview of the metatags on all of their content.

Marking this RTBC.

  • DamienMcKenna committed 4adc1bb on 7.x-1.x
    Issue #1906578 by DamienMcKenna, andyg5000, Leo Pitt, arpas, nikita_tt,...
DamienMcKenna’s picture

Status: Reviewed & tested by the community » Fixed
Issue tags: -Needs tests
Parent issue: » #3112570: Plan for Metatag 7.x-1.28

Committed, with a change to the README.txt and metatag.install to clear the caches. I added #3213270: Add test coverage for the Views field display functionality and #3213271: Make the Views field display functionality work with all languages for follow-on tasks. Thanks everyone!

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.