1

I add a field which type is PDF. When I click the PDF file, I want the PDF file to open in a new window (using target="_blank").

How do I add such target="_blank" to the a label?

2
  • In tour theme's template.php or in a custom module, override the theme_file_link() theme hook to add a target="_blank" attribute to your file links. Commented Dec 1, 2012 at 20:20
  • how to override it .could you give me with more details. thank you,if the theme is test. how to write the override function?
    – 123
    Commented Dec 2, 2012 at 2:31

3 Answers 3

2

If you're looking for a quick fix for ALL pdf links on your site you could use a little bit of javascript to accomplish this as well. This snippet finds all URLs ending in .pdf and sets the target attribute to be _blank (new window).

(function ($) {
    $(document).ready(function() {
        // Open PDF In New Window
        $('a[href$=".pdf"]').attr('target', '_blank');
    });

}(jQuery));

Since you're looking for just files of your field type you could certainly use a less generic selector, such as .field-name-field_pdf a[href$=".pdf"]. Best of luck!

1

Add this to your theme template.php file:

<?php

function yourthemename_file_link($variables) {
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $url = file_create_url($file->uri);
  $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));

  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options = array(
    'attributes' => array(
      'type' => $file->filemime . '; length=' . $file->filesize,
      'target' => '_blank',
    ),
  );

  // Use the description as the link text if available.
  if (empty($file->description)) {
    $link_text = $file->filename;
  }
  else {
    $link_text = $file->description;
    $options['attributes']['title'] = check_plain($file->filename);
  }

  return '<span class="file">' . $icon . ' ' . l($link_text, $url, $options) . '</span>';
}
1
  • All implementations of MYTHEME_file_link() that I have seen, including this one, are variations of the Drupal default implementation. This one adds a target="_blank" attribute to all links. Another one adds it only to files of certain MIME types.
    – tanius
    Commented Oct 17, 2016 at 16:11
1

The FileField Target module takes care of it from now on…

1
  • A nicely integrated and flexible solution, but for it's currently blocked by a WSOD bug.
    – tanius
    Commented Oct 17, 2016 at 15:08

Your Answer

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

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