-
Notifications
You must be signed in to change notification settings - Fork 0
/
wp-pdf-embed.php
40 lines (32 loc) · 1.25 KB
/
wp-pdf-embed.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?php
/**
* Plugin Name: WP PDF Embed
* Description: Renders PDF links as embeds on the frontend.
* Version: 1.0.0
* Author: Robert Andrews
*/
// Filter the content and replace PDF links with embeds
function pdf_embed_filter_content($content)
{
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'));
$xpath = new DOMXPath($dom);
$pdfLinks = $xpath->query('//a[contains(@href, ".pdf")]');
foreach ($pdfLinks as $pdfLink) {
$parentNode = $pdfLink->parentNode;
// Check if the link is the sole content of the parent node
if ($parentNode->childNodes->count() === 1 && $parentNode->firstChild === $pdfLink) {
$embedCode = $dom->createElement('embed');
$embedCode->setAttribute('src', $pdfLink->getAttribute('href'));
$embedCode->setAttribute('type', 'application/pdf');
$embedCode->setAttribute('width', '100%');
$embedCode->setAttribute('height', '950px');
// Add the embed code below the link
$parentNode->appendChild($embedCode);
}
}
$newContent = $dom->saveHTML();
return $newContent;
}
add_filter('the_content', 'pdf_embed_filter_content');