Skip to content

Commit a24aadb

Browse files
authored
Merge pull request #130 from Vrishabhsk/feature/VJ-52-target-blank
Feature : Non-OSI content links open in a new tab [PROD]
2 parents 15428cb + 674f18e commit a24aadb

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

themes/osi/inc/template-functions.php

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,3 +220,43 @@ 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_force_content_links_new_tab( string $content ) {
232+
// Ensure Events Manager plugin is active and functionality for RSVPable events exists.
233+
if ( function_exists( 'em_is_event_rsvpable' ) && ! em_is_event_rsvpable() ) {
234+
// Instantiate the processor.
235+
$processor = new \WP_HTML_Tag_Processor( $content );
236+
237+
// Get the domain of the site without scheme.
238+
$site_domain = wp_parse_url( site_url(), PHP_URL_HOST );
239+
240+
// Loop through all the A tags and parse href to see if it's an external link.
241+
while ( $processor->next_tag( 'A' ) ) {
242+
$href = $processor->get_attribute( 'href' );
243+
$root_domain = wp_parse_url( $href, PHP_URL_HOST );
244+
245+
// If root domain is null, it's an internal link (no host), skip.
246+
if ( null === $root_domain ) {
247+
continue;
248+
}
249+
250+
// If the root domain is not the same as the site domain, it's an external link.
251+
if ( $root_domain !== $site_domain ) {
252+
$processor->set_attribute( 'target', '_blank' );
253+
}
254+
}
255+
256+
$content = $processor->get_updated_html();
257+
}
258+
259+
return $content;
260+
}
261+
262+
add_filter( 'the_content', 'osi_force_content_links_new_tab' );

0 commit comments

Comments
 (0)