Camen Design Forum

Delete

(Leave this as-is, it’s a trap!)

To delete this post you must be either the original author or a designated moderator.
The content of the post will be removed but the name and date will remain.

  • The post will be removed completely from the thread, rather than blanked
  • Only posts on the last page of the thread can be removed completely (so as to not break permalinks)

RE[22]: embedd youtube videos?

Martijn

Just like the above avatar code, this goes into your `theme.php` file and then in the `theme_custom` function. This was specifically catered to the Greyscale theme. It replaces YouTube links (the different ones I could think of, at least) into actual YouTube embeds if they are the only thing on a line.

It also replaces URLs to images into `IMG` elements. Not because it was requested but because I wanted to show how you could extend both the regular expression and the `if`s to allow other type of links to be replaced. E.g. you could adapt it to embed tweets or other video services.

%
foreach ($template->query('//article/div/p[a and count(*)=1 and not(normalize-space(text()))]') as $node) {
		$link = trim($node->nodeValue);
		$replace = false;

		if (
			preg_match('~(?:
				https?://(?:www\.)?youtu(?:be\.com/(?:embed/|watch\?(?:.+&)?v=)|\.be/)([a-z0-9_\-]+) # Parsing YouTube URLs.
				|
				(.+\.(?:png|jpe?g|gif)) # Parsing image URLs.
			)~ixA', $link, $matches)
		) {
			if (strlen($matches[1])) { // We found a YouTube video.
				$replace = '<iframe width="480" height="360" src="http://www.youtube-nocookie.com/embed/' . $matches[1] . '?autoplay=0&amp;rel=0" frameborder="0" allowfullscreen="allowfullscreen">' . safeHTML($link) . '</iframe>';
			} else if (strlen($matches[2])) { // We found an image link.
				$replace = '<a href="' . safeHTML($link) . '"><img src="' . $matches[2] . '" alt="' . safeHTML($link) . '" /></a>';
			}
		}

		if ($replace) {
			$frag = $node->ownerDocument->createDocumentFragment();
			if (!@$frag->appendXML($replace) || !@$node->parentNode->replaceChild($frag, $node)) {
				throw new Exception("Invalid HTML");
			}
		}
	}
%

There are probably problems with this. I’ve only done minor testing. And you will need to change your CSS yourself if you want anything special.

Note: this is a *template* modifier and runs on the HTML given to the browser. Inside your RSS you will still be seeing the normal URL.

:: @Martijn added on 11 Jul ’13 · 22:08

I think I made a small mistake. Change this:

% Original line #9
				(.+\.(?:png|jpe?g|gif)) # Parsing image URLs.
%

Into this:

% New line #9
				(.+\.(?:png|jpe?g|gif)$) # Parsing image URLs.
%

Guess I should invest in a good Regex editor sometime soon, as soon as I have the cash. Something like http://brettterpstra.com/2013/07/01/mac-app-review-oyster/. Anyone know any good free alternatives?

Your friendly neighbourhood moderators: Kroc, Impressed, Martijn