Skip to content

Instantly share code, notes, and snippets.

@erubio0
Last active September 27, 2024 14:44
Show Gist options
  • Save erubio0/61127eefdfe7e1157d1e175a26e96d98 to your computer and use it in GitHub Desktop.
Save erubio0/61127eefdfe7e1157d1e175a26e96d98 to your computer and use it in GitHub Desktop.
TubeNail Wordpress plugin. Replaces any Youtube URL with its corresponding thumbnail, avoiding embedded content.
<?php
/*
* Plugin Name: TubeNail
* Description: Replaces any Youtube URL with its corresponding thumbnail, avoiding embedded content.
* Version: 1.1
* Author: Emilio Rubio Rigo
* Author URI: https://emilioblog.com
* License: GPLv3
* License URI: https://www.gnu.org/licenses/gpl-3.0.html
*/
// 3rd party tricks: regex https://stackoverflow.com/a/78374748, CSS https://stackoverflow.com/a/37424730, SVG compression https://vecta.io/nano
function TubeNail_function($text) {
$pattern = '/(https?:\/\/)?(((m|www)\.)?(youtube(-nocookie)?|youtube.googleapis)\.com.*(v\/|v=|vi=|vi\/|e\/|embed\/|shorts\/|user\/.*\/u\/\d+\/)|youtu\.be\/)([_0-9a-z-]+)/im';
$replacement = <<<'EOD'
<style>
.tn-container {
text-align: center;
margin-bottom: 1.6em;
}
.tn-video {
position: relative;
display: inline-block;
}
.tn-video:before {
content: "";
position: absolute;
width: 100%;
height: 100%;
z-index: 10;
background: transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 135.467 135.467' height='512' width='512' %3E%3Ccircle r='67.733' cy='67.733' cx='67.733' fill='%230170b9' fill-rule='evenodd'/%3E%3Cpath d='M111.531 67.733L78.715 86.68l-32.816 18.946V67.733 29.841l32.816 18.946z' fill='%23fff' stroke='%23fff' stroke-width='7.408' stroke-linejoin='round'/%3E%3C/svg%3E") center center no-repeat;
background-size: 25%;
}
</style>
<div class='tn-container'>
<a class='tn-video' href='https://youtube.com/watch?v=${1}' target='_blank'><img src='https://img.youtube.com/vi/${1}/hqdefault.jpg'></a>
</div>
EOD;
$text = preg_replace($pattern, $replacement, $text);
return $text;
}
add_filter('the_content', 'TubeNail_function');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment