Last active
August 20, 2022 04:10
-
-
Save pagelab/50b9b3f3f972a72636eb6f757d588068 to your computer and use it in GitHub Desktop.
Adding a class to external links in content blocks.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace MyPlugin; | |
// Adds a class to external links in content blocks. | |
add_filter( 'render_block', __NAMESPACE__ . '\\add_class_external_links', 10, 2 ); | |
/** | |
* Adds a CSS class to external links in content blocks. | |
* | |
* @link https://developer.wordpress.org/reference/hooks/render_block/ | |
* @param $block_content string The block content about to be appended. | |
* @param $block array The full block, including name and attributes. | |
* @return string | |
*/ | |
function add_class_external_links( $block_content, $block ) { | |
// List of content blocks. | |
$blocks = [ | |
'core/heading', | |
'core/paragraph', | |
'core/quote', | |
'core/pullquote', | |
'core/preformatted', | |
'core/list', | |
'core/table', | |
]; | |
// Cancel early if necessary. | |
if ( ! in_array( $block['blockName'], $blocks ) ) return $block_content; | |
// Get this domain. | |
$url = parse_url( site_url() ); | |
$domain = $url['host']; | |
// Let's start the content parser. | |
$dom = new \DOMDocument('5.0', 'utf-8'); | |
// Enable libxml errors. | |
$internal_errors = libxml_use_internal_errors( true ); | |
// Need to force conversion to specific encoding standard to prevent errors. | |
$dom->loadHTML( mb_convert_encoding( $block_content, 'HTML-ENTITIES', 'UTF-8' ) ); | |
libxml_use_internal_errors( $internal_errors ); | |
$xpath = new \DOMXPath( $dom ); | |
// Find all links that does not include this site's domain. | |
$links = $xpath->query( "//a[not(contains(@href, '$domain'))]" ); | |
// If there are links to an external domain. | |
if ( ! is_null( $xpath->query( "//a[not(contains(@href, $domain))]" ) ) ) { | |
// Add the class to the link. | |
foreach( $links as $link ) { | |
$link->setAttribute( 'class','epc-external-link' ); | |
} | |
// Save the block content. | |
$block_content = $dom->saveHTML($dom->documentElement); | |
} | |
// Return the original block content. | |
return $block_content; | |
} |
Author
pagelab
commented
Aug 20, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment