For analytics/tracking purposes, I would like to add a custom attribute to a link field. Is there a way to add an additional text field to the link, similar to the title attribute field?

  • What kind of attribute do you want to add? Link fields already have many attributes at their edit form pages (admin/structure/types/manage/ct_name/fields/field_name) like, class, title etc. Moreover do you want that attribute to be editable per node or not? – mchar Nov 16 '16 at 17:21
  • Yes, I would like to add a custom attribute (other than class or title) which is editable per node. This will be used for link tracking/analytics purposes. – Mark Anderson Nov 16 '16 at 17:25
  • 1
    I can propose you the field_collection module, which is quite easy to set it up or to go with your own custom implementation of another field which cannot be developed in a comment of course. For both solutions you'll have to bind that attribute to your link I guess. – mchar Nov 16 '16 at 17:33

On Drupal 7 there are several ways to go about this depending on your setup.

If you are using Display Suite you can add custom attributes to the link field (and all the various wrappers) by setting the field template to Expert: Display Suite Link Settings

You could also use template_preprocess_field() in a module or your theme to add additional attributes to the link before it is rendered.

Display Suite is more limiting but often easier (particullarly if it is already in use). Since the preprocess function is in PHP it will give you more flexibility that may or may not be useful.

  • Thank you for posting an answer. Although I'm not sure if those solutions will work in my case. The attribute value needs to be entered into a textfield on the node edit form by a Drupal user. That's why I was wondering if it's possible to add an additional textfield there. It would be similar to the title attribute field. – Mark Anderson Nov 16 '16 at 17:14
  • 1
    For that you'll want to use a preprocess function, likely on the content type instead of the field (although details matter here). The advantage of doing it in the preprocess is that you pull data from other places -- like other fields -- more easily. – acrosman Nov 16 '16 at 18:16

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.