Skip to content

Commit 1ceb571

Browse files
committed
Open non-osi content links on new tab
1 parent 654c9b5 commit 1ceb571

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

themes/osi/inc/template-functions.php

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,3 +220,42 @@ function osi_the_page_dates() {
220220
}
221221
}
222222
}
223+
224+
/**
225+
* Force external links to open in new tab.
226+
*
227+
* @param string $content The content to process.
228+
*
229+
* @return string The processed content.
230+
*/
231+
function osi_the_content( $content ) {
232+
if ( ! em_is_event_rsvpable() ) {
233+
// Instantiate the processor.
234+
$processor = new \WP_HTML_Tag_Processor( $content );
235+
236+
// Get the domain of the site without scheme.
237+
$site_domain = wp_parse_url( site_url(), PHP_URL_HOST );
238+
239+
// Loop through all the A tags and parse href to see if it's an external link.
240+
while ( $processor->next_tag( 'A' ) ) {
241+
$href = $processor->get_attribute( 'href' );
242+
$root_domain = wp_parse_url( $href, PHP_URL_HOST );
243+
244+
// If root domain is null, it's an internal link (no host), skip.
245+
if ( null === $root_domain ) {
246+
continue;
247+
}
248+
249+
// If the root domain is not the same as the site domain, it's an external link.
250+
if ( $root_domain !== $site_domain ) {
251+
$processor->set_attribute( 'target', '_blank' );
252+
}
253+
}
254+
255+
return $processor->get_updated_html();
256+
}
257+
258+
return $content;
259+
}
260+
261+
add_filter( 'the_content', 'osi_the_content' );

0 commit comments

Comments
 (0)