Встройщик видео

add_filter('acf/format_value/type=text', 'do_shortcode');
add_filter('acf/format_value/type=textarea', 'do_shortcode');
add_filter('acf/format_value/type=wysiwyg', 'do_shortcode');
add_filter('the_content', 'do_shortcode');
add_filter('the_excerpt', 'do_shortcode');
add_filter('the_title', 'do_shortcode');

function blue_shortcode($atts, $content = null) {
    return '<span class="blue-text">' . do_shortcode($content) . '</span>';
}
add_shortcode('blue', 'blue_shortcode');

function theme_custom_scripts() {

    wp_enqueue_script(
        'phone-mask',
        get_stylesheet_directory_uri() . '/assets/js/phone-mask.js',
        array(),
        '1.0',
        true
    );

}
add_action('wp_enqueue_scripts', 'theme_custom_scripts');

function messengers_shortcode() {
    if (!function_exists('have_rows')) return '';

    ob_start();

    if (have_rows('messengers', 'option')) {
        echo '<div class="messengers-list">';

        while (have_rows('messengers', 'option')) {
            the_row();

            $icon = get_sub_field('icon');
            $link = get_sub_field('link');

            if ($icon && $link) {
                $icon_url = is_array($icon) ? $icon['url'] : $icon;

                echo '<a href="' . esc_url($link) . '" target="_blank" rel="noopener noreferrer">';
                echo '<img src="' . esc_url($icon_url) . '" alt="">';
                echo '</a>';
            }
        }

        echo '</div>';
    }

    return ob_get_clean();
}
add_shortcode('messengers', 'messengers_shortcode');

//вывод документов
function acf_documents_shortcode() {

    ob_start();

    if (have_rows('documents')): ?>

        <div class="acf-documents-grid">

        <?php while (have_rows('documents')): the_row();

            $title = get_sub_field('title');
            $file  = get_sub_field('file');

            if (!$file) continue;

            // нормализуем ID
            $file_id = is_array($file) ? $file['ID'] : $file;

            // PDF URL
            $url = wp_get_attachment_url($file_id);

            // размер файла
            $size = '';
            $path = get_attached_file($file_id);
            if ($path && file_exists($path)) {
                $size = size_format(filesize($path));
            }

        ?>

            <div class="acf-doc-item">

                <a class="acf-doc-link"
                   href="<?php echo esc_url($url); ?>"
                   target="_blank"
                   rel="noopener">

                    <!-- ВАЖНО: используем WP стандартный attachment image (как делает Impreza) -->
                    <div class="acf-doc-preview">
                        <?php echo wp_get_attachment_image($file_id, 'full'); ?>
                    </div>

                    <?php if ($title): ?>
                        <div class="acf-doc-title">
                            <?php echo esc_html($title); ?>
                        </div>
                    <?php endif; ?>

                    <div class="acf-doc-meta">
                        <div class="meta-title">Скачать PDF </div><?php if ($size) echo "({$size})"; ?>
                    </div>

                </a>

            </div>

        <?php endwhile; ?>

        </div>

    <?php endif;

    return ob_get_clean();
}

add_shortcode('acf_documents', 'acf_documents_shortcode');


// =========================
// УНИВЕРСАЛЬНОЕ ВСТРАИВАНИЕ ВИДЕО
// YouTube / VK / Дзен / Rutube / OK
// =========================


// Стили
add_action('wp_head', function() { ?>
<style>
.video-embed{
	position:relative;
	width:100%;
	max-width:100%;
	aspect-ratio:16/9;
	margin:2rem 0;
	border-radius:10px;
	overflow:hidden;
	background:#000;
}

.video-embed iframe,
.video-embed video{
	width:100%;
	height:100%;
	border:0;
	display:block;
	border-radius:10px;
}

@media(max-width:768px){
	.video-embed{
		margin:1.5rem 0;
		border-radius:10px;
	}
}
</style>
<?php });


// =========================
// ОБРАБОТКА КОНТЕНТА
// =========================

function universal_video_embed_for_editor($content) {

	if (empty($content) || !is_string($content)) {
		return $content;
	}

	$wrap = function($html) {
		return '<div class="video-embed">' . $html . '</div>';
	};

	$pattern_any_url = '~(^|[\s>])((https?://)[^\s<]+)(?=$|[\s<])~iu';

	$content = preg_replace_callback($pattern_any_url, function($m) use ($wrap) {

		$prefix = $m[1];
		$url    = trim($m[2]);

		$trail = '';

		if (preg_match('~[)\],.!?]+$~u', $url, $mm)) {
			$trail = $mm[0];
			$url = preg_replace('~[)\],.!?]+$~u', '', $url);
		}

		$html = universal_video_embed_build_html($url);

		if ($html) {
			return $prefix . $wrap($html) . $trail;
		}

		return $prefix . $m[2] . $trail;

	}, $content);

	return $content;
}


// =========================
// ПАРСЕР ВИДЕО
// =========================

function universal_video_embed_build_html($url) {

	if (!$url || !is_string($url)) return '';

	$url = html_entity_decode($url, ENT_QUOTES, 'UTF-8');


	// YouTube
	if (preg_match('~https?://(?:www\.)?(?:youtube\.com/(?:watch\?v=|embed/|shorts/)|youtu\.be/)([A-Za-z0-9_-]{6,})~i', $url, $m)) {

		$vid = $m[1];
		$src = 'https://www.youtube.com/embed/' . esc_attr($vid);

		return '<iframe src="' . esc_url($src) . '" loading="lazy" allowfullscreen></iframe>';
	}


	// OK.ru
	if (preg_match('~https?://(?:www\.)?ok\.ru/video/(\d+)~i', $url, $m)) {

		$src = 'https://ok.ru/videoembed/' . esc_attr($m[1]);

		return '<iframe src="' . esc_url($src) . '" loading="lazy" allowfullscreen></iframe>';
	}


	// Rutube
	if (preg_match('~https?://(?:www\.)?rutube\.ru/(?:video|play/embed)/([A-Za-z0-9]+)~i', $url, $m)) {

		$src = 'https://rutube.ru/play/embed/' . esc_attr($m[1]);

		return '<iframe src="' . esc_url($src) . '" loading="lazy" allowfullscreen></iframe>';
	}


	// Дзен
	if (preg_match('~https?://(?:www\.)?(?:dzen\.ru|m\.dzen\.ru)/(?:video/watch/|embed/)([A-Za-z0-9_-]+)~i', $url, $m)) {

		$src = 'https://dzen.ru/embed/' . esc_attr($m[1]);

		return '<iframe src="' . esc_url($src) . '" loading="lazy" allowfullscreen></iframe>';
	}


	// VK
	if (preg_match('~https?://(?:www\.)?(?:vk\.com|vkvideo\.ru)/video(-?\d+)_(\d+)~i', $url, $m)) {

		$oid = $m[1];
		$vid = $m[2];

		$cache_key = 'uvk_oembed_' . md5($url);
		$cached = get_transient($cache_key);

		if (is_string($cached) && $cached !== '') {
			return $cached;
		}

		if (function_exists('wp_oembed_get')) {

			$o = wp_oembed_get($url, array('width' => 960));

			if (is_string($o) && $o !== '') {
				set_transient($cache_key, $o, DAY_IN_SECONDS);
				return $o;
			}
		}

		$src = add_query_arg([
			'oid' => $oid,
			'id'  => $vid,
		], 'https://vk.com/video_ext.php');

		return '<iframe src="' . esc_url($src) . '" loading="lazy" allowfullscreen></iframe>';
	}

	return '';
}


// =========================
// ФИЛЬТРЫ (ТОЛЬКО ОСНОВНЫЕ)
// =========================

add_filter('the_content', 'universal_video_embed_for_editor', 20);
add_filter('get_the_excerpt', 'universal_video_embed_for_editor', 20);
add_filter('term_description', 'universal_video_embed_for_editor', 20);