I am using the WYSIWYG module to load TinyMCE 4.x, I am then uploading an image via the Media button in the toolbar of TinyMCE finally I am using LinkIt to link the image to a location.

All of this is fine inside the WYSIWYG editor, but once it is published and viewed on the page the wrapping <a> tag is stripped.

So in the editor if I view the source I see:

<a href="/my-exciting-page/index.html">
        [[{"fid":"7","view_mode":"default","fields":{"format":"default","field_file_image_alt_text[und][0][value]":"","field_file_image_title_text[und][0][value]":""},"type":"media","link_text":null,"attributes":{"height":376,"width":640,"class":"media-element file-default"}}]]
    </a>

However once this is rendered to the template I see simply:

<img height="376" width="640" class="media-element file-default" typeof="foaf:Image" src="http://example.org/sites/default/files/miscl.jpg" alt="" />

If I then edit this piece of content again and view the source of the WYSIWYG editor the <a> tag is definitely still wrapped around the Media module's little string of JSON.

In a bid to prevent this from happening I changed the Wysiwyg Profiles and Text Profiles so that they don't remove broken tags or attempt to clean up an HTML or introduce any of their own HTML. Unfortunately this has had no effect.

Is there some way that Media/Drupal/WYSIWYG/LinkIt can be setup so that it will allow images to be linked? I have been unable to find a relevant issue or patch floating about out there on the web either.

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

Anonymous’s picture

Issue summary: View changes
gmclelland’s picture

I don't think TinyMCE 4.x is supported yet with the wysiwyg module. Maybe you can try 3.5.8 and see if it works?

Anonymous’s picture

@gmclelland the WYSIWYG editor is working fine with the wysiwyg module with the appropriate patch mentioned in their documentation. This looks an issue with the conversion of the Media tags. Manually inputting the link and image via HTML source works just fine and saves to the DB so this doesn't appear to be an issue with the editor or the filters that are enabled in the wysiwyg text format/profile.

Anonymous’s picture

Having looked more closely at this it looks like the issue is actually that the image is being wrapped with code and contextual links. This appears to then break the <a> wrapping the image.

So the problem line of code causing this is in media_wysiwyg.filter.inc within the media_wysiwyg_token_to_markup() function. Towards the bottom it attempts to make a decision of whether or not to add wrapping divs to the image:

    if (count(element_children($element['content'])) > 1) {
      // Add surrounding divs to group them together.
      // We dont want divs when there are no additional fields to allow files
      // to display inline with text, without breaking p tags.
      $element['content']['#type'] = 'container';
      $element['content']['#attributes']['class'] = array(
        'media',
        'media-element-container',
        'media-' . $element['content']['file']['#view_mode']
      );
    }

Unfortunately, in my case count(element_children($element['content'])) returns 2 even though there is only one media element in there. This is because in contributions/file_entity/file_entity.file_api.inc the file_build_content() function ( http://drupalcontrib.org/api/drupal/contributions%21file_entity%21file_e...) it is adding an array index with the key "links".

So even though there aren't multiple elements it still tries to wrap the image with

s. It appears to me that this would never have worked as file_build_content() is always returning two array keys that aren't prefixed with a #. This is apparently the way that element_children() knows what to extract from the array - it ignores keys prefixed with a #.

Anyway tl;dr the contents of that if statement are always executed no matter whether there are multiple media items or not. Can we just bump this check to greater than 2 or is there another reason this is set to 1?

Anonymous’s picture

This issue is mostly caused by the file_entity module. To work round this I have restricted the view modes available to media_wysiwyg in /admin/config/media/wysiwyg-view-mode. I have set images to only allow the WYSIWYG view mode like so:

Only local images are allowed. or alternatively see http://imgur.com/WorqfOT

I have then created an override template for the file entity called file--image--wysiwyg.tpl.php (see https://www.drupal.org/node/1793548) and I have the following code in it:

<?php

hide($content['links']);
print render($content);

This has now removed all the annoying links, headers and wrapping <div>s from the output EXCEPT for the media_wysiwyg wrapping <div> mentioned in comment #4.

As this is just one wrapping <div> and the page is HTML this now no longer breaks the link, but it would still be preferable to be able to remove this annoying wrapping <div>.

theMusician’s picture

I can confirm this is an issue as well with CKeditor 4, file entity 7.x-2.0-beta1, and 7.x-2.0-alpha4. Treffynnon's fix does not seem to work with this setup either.

ayalon’s picture

Thanks @Treffynnon for debugging this and for the fix. I also invested hours but did not come to your solution.

@theMusician:
Treffynnons solutions works but he forgot to mention one important step.

You need two template files, because of a long existing bug in drupal:
file--image.tpl.php (copied over form file_entity.tpl.php)
file--image--wysiwyg.tpl.php (see above)

The second file only works, if you have the first file in your theme folder. Then clear the cache and your ready to fly also in CKeditor

theMusician’s picture

Thanks for the tip @ayalon. I'll give it a try when I do my next set of upgrade tests.

Zythyr’s picture

I think I am having a similar issue: https://www.drupal.org/node/2378685

What are these template files and where do I get them? And where to I put them?
file--image.tpl.php
file--image--wysiwyg.tpl.php

Will that resolve the issue I am having? Will Media module be updated to resolve this issue?

BrightBold’s picture

@zythry - You copy /sites/all/media/modules/file_entity/file_entity.tpl.php into the templates folder in your theme, and rename it file--image.tpl.php. Then, you make a copy of that, also in /sites/all/themes/yourtheme/templates, and name it file--image--wysiwyg.tpl.php (or replace "wysiwyg" with name-of-your-view-mode if your view mode isn't named wysiwyg, using a single hyphen in between words if your view mode has multiple words in its name). You edit the latter template as desired.

Zythyr’s picture

@BrightBold
Sorry I don't have a way to test it at the moment, but will your suggestion fixed the issue that I posted here: https://www.drupal.org/node/2378685

If so, why isn't Media module being updated to fix this issue? (I am sorry if I asked a stupid question, I don't know much about development).

Zythyr’s picture

@BrightBold

I just did what you said, however, instead I copied the file into /themes/bartik/templates because I am using the default theme. Bartik doesn't exist in the /sites/all/themes/ folder.

Your suggestion still didn't fix the issue I posted here: https://www.drupal.org/node/2378685. I looked at the HTML code in the Ckeditor by click on the "Source" button. It inputs the IMG tags properly, but there is no A tag created for linking...

pdcrane’s picture

I'm having this same issue as well. Treffynnon's fix worked perfectly for me.

Running:
Media 7.x-2.0-alpha4+14-dev
File Entity 7.x-2.0-beta1+13-dev
WYSIWYG 7.x-2.2+54-dev
CKEditor 4.2.0.f74e558

I patched two Media module files:
/media/includes/media.filter.inc
/media/modules/media_wysiwyg/includes/media_wysiwyg.filter.inc

to change:
if (count(element_children($element['content'])) > 1) {
to
if (count(element_children($element['content'])) > 2) {

This resolved the issue for me across the board. No template changes necessary.

drupal a11y’s picture

Within "Media 7.x-2.0-alpha4+19-dev (2015-Jan-08)" and also the named version above I can´t find a "media/includes/media.filter.inc"-file.

There´s only the one in "media/modules/media_wysiwyg/includes/media_wysiwyg.filter.inc".

Patching this file without additional theme-templates does not solve the issue for me.

I tried these versions:
Media 7.x-2.0-alpha4+14-dev / Media 7.x-2.0-alpha4+19-dev
File Entity 7.x-2.0-beta1+13-dev
WYSIWYG 7.x-2.2+54-dev
CKEditor 4.4.3 / 4.4.6

Also I have "Media WYSIWYG View Mode" disabled.

drupal a11y’s picture

I also found out that the "formats order" is important for the resulting markup: admin/config/content/formats/

1. Convert URLs into links
2. Convert line breaks into HTML
3. Convert Media tags to markup

Otherwise the markup has unwanted results.

focal55’s picture

Thanks @mori, the format orders fixed the issue for me.

BrightBold’s picture

@Zythyr - We should be addressing the other problem you're experiencing in its own issue, rather than cluttering up this one (although it seems to have been deleted? The links you posted don't work). My instructions were to help implement Treffynnon's workaround for this issue as posted in #5.

But, as an aside, you shouldn't be modifying Bartik as you will lose all your changes when you upgrade Drupal. Instead, follow the instructions for creating a sub-theme of Bartik and move all your modifications over to your new child theme.

lecler’s picture

Same problem for me.

My workaround :

  • Copy modules/file_entity/file_entity.tpl.php as file--image.tpl.php in my theme
  • Removed lines
    <?php if (!$page): ?>
        <h2<?php print $title_attributes; ?>><a href="<?php print $file_url; ?>"><?php print $label; ?></a></h2>
      <?php endif; ?>
AlMiesel’s picture

lecler, thanks this worked for me!

denix’s picture

Thanks! workaround #18 worked for me too!

seanpclark’s picture

What is the use case of wrapping multiple items in a div when using a wysiwyg? The comment for the media-element-container code says "We dont want divs when there are no additional fields to allow files to display inline with text, without breaking p tags," so I'm confused because this would mean content can't be placed in a paragraph tag because it will get ejected by the browser. An img tag, however, is valid on an intra-paragraph level.

dasginganinja’s picture

Sean P. Clark, I think that it could be used for things like contextual links. Just as an example.

seanpclark’s picture

For contextual links, there is a separate wrapper (contextual-links-wrapper) for that purpose.

For multiple fields on a media item, a field group can be used instead – that’s the only situation that comes to mind for me.

Isn’t count(element_children($element['content’])) going to always return > 1 because it’d include ‘file’ and the ‘links’ array? Maybe the original intent was to do as #13 mentioned and check if count is greater than 2. Either way, I prefer the media-element-container wrapper be omitted (in favor of field groups) if the idea was to just wrap multiple fields.

eigentor’s picture

The combination of #13 and an extra template file named file--image--wysiwyg.tpl.php solved the issue.
Using the latest CKEditor 4.5.2 and File Entity 7.x-2.0-beta2

Inside the template I chose a rather radical approach like described by treffynon in #5, removing all div wrappers and just having

 hide($content['links']);
 print render($content);

I did this because in my use case I have no extra fields around images in text areas and I don't want contextual links.
Then there was the extra div around the media element with the class media-element-container that cannot be removed by just creating the template. This is removed by changing media_wysiwyg.filter.inc like described in #13. This appears to be clearly a bug, as pointed out by treffynon in #4.
In my case raising the count to 2 was enough.

It seems like file entity went a bit overboard here. The use case of multiple fields in a media element are to be solved, like when you have captions and stuff, but creating problems for simple images inserted into text areas by wrapping a lot of unnecessary html around it. And this specifically in the wysiwyg view mode that is meant to cater to Wysiwyg editors.

dasginganinja’s picture

Using the above instructions in #24 got this working for me. I do also feel that this is a bug as there is clearly a logic error.

For the time being I'm including file.tpl.php and file--image--wysiwyg.tpl.php in my base theme along with a patch for media_wysiwyg in the Drush make file until this is resolved.

joelstein’s picture

FYI, to also remove the wrapper DIV provided by Media, you can do something like this in a custom module hook (it won't work in a theme's template.php file, because theme don't have access to drupal_alter() hooks):

/**
 * Implements hook_file_view_alter() from File Entity.
 */
function mymodule_file_view_alter(&$build, $type) {
  if ($build['#bundle'] === 'image') {
    unset($build['links']);
  }
}

Ideally, though, Media wouldn't add these tags if using File Entity as the render method unless the element_children() were greater than 2 (not 1).

makbeta’s picture

IMHO media module should give users an option what type of a tag should it wrap content or not render any at all. Alternatively the wrapping tag should at least be a , which is the same block type element as an <img>, thus not rendering illegal markup by default.

Here is an example of a case where I don't want media module to render any tags. I created my own caption field and used the file entity module to do the markup of image & caption. Using <figure> & <figcaption> tags. While my element now will have more than 2 children I still don't want the wrapping <div> to show up because I already have all the markup I need.

rich_dawson’s picture

#26 works for me, thank you for that joelstein

DigitalFrontiersMedia’s picture

As a quick workaround, going to /admin/config/media/browser, selecting "Legacy Rendering", saving configuration, and clearing caches will likely fix the broken anchor tag wrappings...without the need for swapping out file entity tpl.phps and such.

vood002’s picture

Interestingly I'm having this issue with the dev version of media and TinyMCE 3.5.8. I've tried all of the above solutions with no luck.

  • I was already using a stripped down file--image.tpl.php so no change there.
  • I attempted to change to legacy mode in the media browser, no luck
  • I rearranged my input filters as recommended, no dice.
  • I attempted changing if (count(element_children($element['content'])) > 1) in media_wysiwyg.filter.inc, but it was only finding one child anyway. I presume this is the root of my problem, most issues in this thread due to this child count being >=2 but mine is stemming from somewhere else
  • I attempted unchecking "remove source formatting" and removing "correct faulty and chopped off html" and neither had any effect.

A little perplexed here. Looks like most of this thread is using CK so I'm assuming that's where my issue comes from. If anyone has any suggestions I'd appreciate them. Thanks!

edit: formatting

jbiechele’s picture

This is just to confirm that the workaround from DigitalFrontiersMedia in comment #29 fixed it on my site. Thank you very much for the hint!

kobuk’s picture

Following #29 also removed all the extra markup for me.

TinyMCE 3.5.8
wysiwyg 7.x-2.2
Media 7.x-2.0-beta1+9-dev
File Entity 7.x-2.0-beta2+13-dev

davidwbarratt’s picture

I'm trying to think of a way to fix this for everyone and the only thing I can think to do is take the WYSIWGY view mode and (by default) strip out all the wrappers from the template. If someone wants them back in their template they can add them back, or if they want to use a different view mode they can remove them.

Does that sound like a plan?

DigitalFrontiersMedia’s picture

@davidwbarratt : sounds reasonable to me but I don't think I deal with it enough to anticipate any of the consequences. So I'd like to hear other thoughts on the matter.

davidwbarratt’s picture

Status: Active » Needs review
FileSize
4.88 KB

Perhaps something like this?

davidwbarratt’s picture

Attached is a patch for the current stable release 7.x-2.0-beta1.

Fabianx’s picture

There is another way to circumvent this: (untested, but should work)

/**
  * Implements hook_file_view().
  */
function mymodule_file_view($file, $view_mode, $langcode) {
  if ($view_mode != 'full' || !file_entity_is_page($file)) {
    unset($file->content['links']);
  }
}

/**
  * Implements hook_preprocess_file_entity().
  */
function mymodule_preprocess_file_entity(&$variables) {
  // Ensure the links key exists.
  if (!isset($variables['content']['links'] )) {
    $variables['content']['links'] = array();
  }
}

Could also use file_view_alter() with a high weight instead if there is conflict with contrib modules trying to add to 'links', e.g:

/**
  * Implements hook_file_view_alter().
  */
function mymodule_file_view_alter(&$build) {
  if ($build['#view_mode'] != 'full' || !file_entity_is_page($build['#file'])) {
    unset($build['links']);
  }
}

/**
  * Implements hook_preprocess_file_entity().
  */
function mymodule_preprocess_file_entity(&$variables) {
  // Ensure the links key exists.
  if (!isset($variables['content']['links'] )) {
    $variables['content']['links'] = array();
  }
}

brockfanning’s picture

In my opinion it's going to be impossible to have a solution that keeps divs out of the rendered file entity. As has been mentioned, the stock file_entity template has div wrappers, and the media module also adds a div wrapper. On top of that, any fields that are output along with the file entity will have div wrappers around them too. Of course it's possible to override all of the related templates and control the markup such that there are no divs, but we can't expect everyone to go to those lengths.

I would take a step back and look at what the actual problem is. I don't think there is a problem with divs being inside of anchor tags. HTML doesn't mind this. Unless I'm mistaken, the problem is when the file entity appears inside an anchor tag inside a paragraph tag. The divs, in that case, cause browsers to close the opening paragraph tag just before the opening div, which is after the opening anchor; and that causes the anchor to close, and things get wacky. So for example this:

<p>
  <a href="foo.html">
    <div><img src="bar.jpg" /></div>
  </a>
</p>

gets changed (in the browser) to this:

<p>
  <a href="foo.html"></a>
</p>
  <div><img src="bar.jpg" /></div>
<a href="foo.html"></a>

So one option might be to ensure that media tokens don't get wrapped in paragraph tags, which is what I've tackled here: #2707107: Cannot put link on an image added with media

I do think that #18 above is an issue. HTML definitely does not like anchor tags inside of anchor tags. Personally I think that the stock file_entity template should have that link removed. But, at this point it's possible that some sites rely on it.

suffering drupal’s picture

After a decade of being stuck it still strikes me how Drupal manages to frequently turn even the simplest things into dramaticly complex and despairing.
More so with Media, which I only have dared to use as is because all of the problems it generates if you touch anything. But after leaving it for lost for some years, I now spent two days on something as basic, simple, and stupid as adding a link to an image! Something so fundamental you just can't get around it.

Anyway I just wanted to confirm that #29 finally allowed me to actually have a link from images indeed!!! To be more specific, personalized still images from videos to those videos. What I am not sure of yet, is if it has broken anything somewhere else.
Now I wonder why the "Full file entity rendering" actually exists and is even default, with all the problems it delivers, as the many and years-old issues confirm. I guess one of the many misteries of Drupal. I just hope it will not take days or years again to discover the next step: how to open those videos either in lightbox or colorbox, although the first tryouts doing as told do not give any results as promised or expected either.

daften’s picture

@brockfanning, so basically this can be closed as a duplicate of #2707107 ?

joseph.olstad’s picture

joseph.olstad’s picture

@daften , it looks like there's a configuration that fixes this, please try this:
Configure the media_filter_paragraph_fix filter as described:

This filter will strip any paragraph tags surrounding embedded Media tags. This helps to avoid the chopped up markup that can result from unexpectedly closed paragraph tags. This filter should be positioned above (before) the "Convert Media tags to markup" filter.

joseph.olstad’s picture

Status: Needs review » Closed (duplicate)

If anyone is still experiencing this, please upgrade to the latest version of media
and also upgrade to the latest version of file_entity

otherwise is a possible duplicate of #2707107: Cannot put link on an image added with media which also may be resolved by upgrading file_entity and media

othermachines’s picture

I've also been tackling the problem of image mark-up being rendered outside of <p></p> tags after being embedded in the wysiwyg editor. My solution is below, which is basically an amalgamation of various suggestions provided above.

Edit: Solution in #42 unfortunately won't do in my case since it doesn't prevent alignment classes from being added to the paragraph tag (by image2, I think?) in the editor. Enabling the filter just removes the paragraph tag which removes the formatting.

1. Copy file_entity/file_entity.tpl.php into your theme folder and rename it file--image.tpl.php. Replace contents with:

<?php
/**
 * @file
 */
?>
<span id="<?php print $id; ?>" class="<?php print $classes ?>"<?php print $attributes; ?>>
  <?php
    // We hide the links now so that we can render them later.
    hide($content['links']);
    print render($content);
  ?>
</span>

2. In your theme's template.php file, add the following (replace THEME with your theme name): Add the following to a custom module* (replace MODULE with your module name):

function MODULE_media_wysiwyg_token_to_markup_alter(&$element, $tag_info, $settings) {
  if ($element['content']['#bundle'] == 'image') {
    unset($element['content']['#type']);
    unset($element['content']['#attributes']);
  }
}

* NOTE: When this hook was in my theme's template.php file it didn't always load in time to be triggered on all media elements. It works more reliably in a custom module.

3. Clear caches.

Before:

<p class="center"></p>
<div class="media media-element-container media-default">
  <div id="file-302" class="file file-image file-image-jpeg">
    <h2 class="element-invisible"><a href="/files/2jpg-0">2.JPG</a></h2>
    <div class="content">
      <img class="img-responsive media-element file-default" src="http://example.com/2_0.jpg" alt="">
    </div>
  </div>
</div>

After:

<p class="center">
  <span id="file-302" class="file file-image file-image-jpeg">
    <img class="img-responsive media-element file-default" src="http://example.com/2_0.jpg" alt="">
  </span>
</p>


Tested with:

media 7.x-2.0-beta14, 7.x-2.0-rc5
media_ckeditor 7.x-2.0-alpha4, 7.x-2.0-rc3+1-dev

joseph.olstad’s picture

Status: Closed (duplicate) » Needs review

#44

joseph.olstad’s picture

had a closer look, alternatively, this would be done best as it was done in patch #35

https://www.drupal.org/files/issues/linked_images-2357993-35.patch

However, patch #35 needs to be rerolled due to changes made since beta8 , media_wysiwyg_view_mode was deprecated and its logic was moved.

So patch #35 is actually the correct approach IMHO, however it needs refactoring. Patch #35 approach would be best because it does not require a custom theme tpl in a theme , rather the tpl would be handled by us in this module as we'd provide the tpl in this module as is done in #35.

joseph.olstad’s picture

Status: Needs review » Needs work

patch #35 needs a reroll / refactoring as I mentioned. media_wysiwyg_view_mode was deprecated , the same logic should go probably into media_wysiwyg instead

othermachines’s picture

Hi, @joseph.olstad. I wasn't actually suggesting #44 as a fix, but a workaround. :)

If you're going to revisit this I would suggest looking at whether to adjust the count (or find some other way to determine if there are multiple images) in media_wysiwyg_token_to_markup() as first suggested by @Treffynnon in #4. It's a small change that at the very least would prevent people from having to implement a hook in order to get rid of all of the block-level elements wrapping the image (which seems to be the root of the problem).

Thx for your hard work on this module!

joseph.olstad’s picture

yes #44 is a valid workaround, no problem, just prefer that we deal with it in the module similar to patch #35 (needs reroll/refactor) . Patch #35 will apply to versions up to beta7 however needs a reroll for beta14

joseph.olstad’s picture

FileSize
4.7 KB

hmm, ok I've refactored patch #35 into patch #50

However now after reading the @FabianX suggestion he suggests another way to resolve this. Not entirely sure which would be the best way yet.

setting #50 for review, I have not actually tested it yet, just a straight reroll /refactoring of #35

joseph.olstad’s picture

Status: Needs work » Needs review
joseph.olstad’s picture

Or, actually #29 proposes a solution that does not require a patch. Perhaps proposed solution in #29 is the best because no code change is required in that case.

more testing needed

bpadaria’s picture

updating media module to latest version i.e. 7-x-2.0-beta14 solved mentioned problem for me.

joseph.olstad’s picture

Category: Bug report » Support request
Status: Needs review » Fixed

marking as support request fixed

Status: Fixed » Closed (fixed)

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

peterg.griffin’s picture

Number #29 works. Thanks!

themaurice’s picture

#18 works great thanks

joseph.olstad’s picture

@themaurice and @peterg.griffin, what version of the media module are you using? @bpadaria says that upgrading solved the problem. Just wondering if this is a regression since beta14 or if you're using something older than that. Currently we're at rc12. Are you using rc12 ? or something older than rc12?

capysara’s picture

I just updated to 7.x-2.0-rc12 and tried the #50 patch. It applied, but it doesn't appear to have worked. My images still don't link.

However, #29 worked! Thanks!

If I'm understanding correctly, #45 & #46 of this issue provide a a good summary of the history of the issue: https://www.drupal.org/node/2194821#comment-9842871 and https://www.drupal.org/node/2194821#comment-9927904.

My question is... if enabling "Legacy rendering" (#29) is a workaround, how do we "switch over to the new rendering"?

Thank you for all the hard work on this!!

veronicaSeveryn’s picture

I am using:

MEDIA 7.x-2.0-rc12
FILE ENTITY 7.x-2.0-beta3
WYSIWYG 7.x-2.3+16-dev (from 2017-03-06)

and the link around MEDIA markup doesn't work for me if applied as is, without any patches to either of the modules. The result will be element rendered by itself, not around media produced markup.

I have followed CONFIG change suggestion in comment #29 and it worked.

brockfanning’s picture

It's been a while since I looked into this, so I can't guarantee all this is 100% accurate, but here are some ideas:

If you are not using "legacy" mode, then the full file entity is being rendered. Here is the default template file that is used for file entities (minus all the comments), file_entity.tpl.php:

<div id="<?php print $id; ?>" class="<?php print $classes ?>"<?php print $attributes; ?>>

  <?php print render($title_prefix); ?>
  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>><a href="<?php print $file_url; ?>"><?php print $label; ?></a></h2>
  <?php endif; ?>
  <?php print render($title_suffix); ?>

  <?php if ($display_submitted): ?>
    <div class="submitted">
      <?php print $submitted; ?>
    </div>
  <?php endif; ?>

  <div class="content"<?php print $content_attributes; ?>>
    <?php
      // We hide the links now so that we can render them later.
      hide($content['links']);
      print render($content);
    ?>
  </div>

  <?php print render($content['links']); ?>

</div>

The main thing to notice is that inside the <h2> there is an <a>.

Which means that if you put a link around some embedded Media, and you are not using legacy mode, and you have not overridden the default file_entity template... then you are going to be rendering a link within a link.

Browsers don't like that, so they (the browsers) try to move things around until it makes sense. This is what gives it the weird behavior where the link does not appear to be around the media, when viewed in a browser "Inspector". However, I think that if you look at the source of the page (such as with CTRL+u) you will see the markup is actually as you would expect (albeit invalid) with a link around a link.

So, if you don't want to use Legacy mode, and you need to have linked embedded Media, you could try overriding the file_entity.tpl.php template in your theme, and remove the <a> tag.

Admittedly this is a lot of words just to get linked media... but hopefully this is helpful.

P.S. Yet another option (and what I have done in the past) is to have a custom field on the file types for a link, and use custom code to wrap the rendered media in that link.

joseph.olstad’s picture

Thanks @brockfanning, your explanation clarifies this perfectly.

joseph.olstad’s picture

Component: Media WYSIWYG » Documentation
Status: Closed (fixed) » Needs review

@brockfanning, we should add your explanation to the documentation pages.
Here
https://www.drupal.org/node/627244

or here somewhere
https://www.drupal.org/node/1793548

StephenRobinson’s picture

can remove the media div:

function mymodule_media_wysiwyg_token_to_markup_alter(&$element, $tag_info, $settings) {
  if(isset($element['content']['#bundle'])){
    if ($element['content']['#bundle'] == 'image') {
      unset($element['content']['#type']);
      unset($element['content']['#attributes']);
    }
  }
}
joseph.olstad’s picture

@StephenRobinson, curious, have you tried this with the 7.x-3.0-alpha7 release as well?

riskid’s picture

#29 worked for me!

emerham’s picture

What if we add a link field to the Media browser's final page where you select the display mode, alignment, Alt Text and Title text that could be a URL. That way while you are finalizing you image you can add the link there and then it could be rendered outright. Then we could in theory add LinkIt to this field if the site has it enabled, or some admin page that would allow them to select either text field or linkit as the option.

othermachines’s picture

@emerham - You should post your idea as a feature request.

emerham’s picture

ok I'll add it as a feature request and look at getting some patches created

joseph.olstad’s picture

Status: Needs review » Closed (outdated)

a new release is comming shortly .

see :
#2881204: Add link field to Embed Page

commonpike’s picture

OK, we now have a link field in the Media browser's final page.

I don't think that is a solution. It's in fact obfuscating things. It is not clear for the editor that using the link icon in the wysiwyg editor will not work as expected. But it's also confusing on other sorts of media (link on an audio element?) or displays (link on the link display ?). So I disabled the field (which is a setting, hurray), and now I am still stuck with this problem.

Solution #44, which is simply override the default file_entity.tpl.php in your own theme to not use block elements and dont show links is just fine.

I don't understand why the media module insists to use block elements and links in their file display, even if it's clearly a problem. Why make things so complex ? But if you must, couldn't you provide an optional, more suitable template, at the same place where 'legacy display' is now provided as an option ? Like

"inline display"
(selecting this display will prevent title, links and block elements being printed, making it easier to use media inline) ?

The inline display could be default when using wysiwyg, or something.

marcoka’s picture

switching to legacy mode isnt really good fix. but i have that error now too after updating all modules to the latest versions.
i also added the media paragraph fix filter and added it above the media filter. did not change anything.

media:Version: 7.x-2.10
file-enity: Version: 7.x-2.4

the code generated on source is

<a href="/funkkopfhoerer-test">[[{"fid":"999","view_mode":"full","fields":{"format":"full","field_file_image_alt_text[und][0][value]":"Funkkopfhoerer  Bild","field_file_image_title_text[und][0][value]":"Funkkopfhoerer  Bild"},"type":"media","field_deltas":{"1":{"format":"full","field_file_image_alt_text[und][0][value]":"Funkkopfhoerer  Bild","field_file_image_title_text[und][0][value]":"Funkkopfhoerer  Bild"}},"link_text":null,"attributes":{"alt":"Funkkopfhoerer  Bild","title":"Funkkopfhoerer  Bild","class":"media-element file-full","data-delta":"1"}}]]</a>

and the final code is broken

<div class="media media-element-container media-full"><a href="/funkkopfhoerer-test">
</a><div id="file-999" class="file file-image file-image-jpeg">
<a href="/funkkopfhoerer-test"></a>
<h2 class="element-invisible"><a href="/funkkopfhoerer-test"></a><a href="/file/funkkopfhoerer-testberichtejpg">funkkopfhoerer-testberichte.jpg</a></h2> 
     
  <div class="content">
    <img alt="Funkkopfhoerer Testberichte Bild" title="Funkkopfhoerer Testberichte Bild" class="media-element file-full image-style-large" data-delta="1" src="/sites/funkkopfhoerer-infos.de/files/styles/large/public/funkkopfhoerer-testberichte.jpg?itok=_iahOigp" width="315" height="116"></div>
  
</div>
</div>

i guess overriding that file_entity template seems to be the only good solution so far :(
So i copied "file_entity.tpl.php" to my "themes" "template" folder and removed:

<h2<?php print $title_attributes; ?>><a href="<?php print $file_url; ?>"><?php print $label; ?></a></h2>

Then i can link images with a tags or with the linkit module

RAWDESK’s picture

#29 solved it too for us, but I am trying to find the view mode settings as indicated by #5 at admin/config/media/wysiwyg-view-mode
This path is no longer accessible (after 4 years).

I would like to have WYSIWYG as the default format to be presented when embedding a file in textual content.
Reason:
After upgrading from 7.x-2.0-unstable3 to 7.x-2.19, horizontally aligned image embeds are by current default format no longer rendered as such but wrapped to next line instead.

Is there still a way to set this somewhere because I cannot find it anymore ?

capysara’s picture

It looks completely different, but I think this is what you're looking for: /admin/structure/file-types/manage/image/edit "WYSIWYG view mode" is a select list towards the bottom.

wranvaud’s picture

Issue tags: -

@RAWDESK if it could help you or someone else here:
To restrict view modes go to each or the view modes and check the box at the bottom "Restrict in WYSIWYG" /admin/structure/file-types/manage/image/file-display
The view mode setting indicated by #5 is now separated into each view mode rather than being centralised in that page.

tyler.frankenstein’s picture

#61 is a great explanation and worked for me!

andrewozone’s picture

I was working through this issue with Content Editors, and found that comment #61 explanation helped to solve our problem adding a link to an image. To fully resolve this issue, I commented out the following HTML in the template file file_entity.tpl.php.

<!-- <h2<?php print $title_attributes; ?>><a href="<?php print $file_url; ?>"><?php print $label; ?></a></h2> -->