Last active
November 17, 2021 22:28
-
-
Save seezee/4d1a4899983b8e0b1ed4eeb30994ed1a to your computer and use it in GitHub Desktop.
2 different ways to add rel="noopener noreferrer" to linked images in WordPress. Could be improved with a check for external links so we can also add "external".
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 | |
/** | |
* Plugin Name: Add Rel to Images | |
* Description: Add rel="noopener noreferrer" to linked images. | |
* | |
* @package There is no package. | |
*/ | |
/** | |
* With jQuery. | |
*/ | |
function my_plugin_inline_script() { | |
wp_add_inline_script( 'jquery', 'jQuery( document ).ready( function( $ ) { $(".external").each(function() { $(".external a").attr("rel", "external noopener") }); });' ); | |
} | |
add_action( 'wp_enqueue_scripts', 'my_plugin_inline_script' ); | |
/** | |
* Vanilla JavaScript | |
*/ | |
wp_register_script( 'set-rel', '', array(), '1.0.0', true ); | |
wp_enqueue_script( 'set-rel' ); | |
wp_add_inline_script( 'set-rel', 'document.querySelectorAll(".external a").forEach((el) => { el.setAttribute("rel", "external noopener"); });' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use with class "external", e.g.,
<div class="external"><a href="" target="_blank"><img src="/path/to/img" width="" height="" alt=""></a></div>